gergelyke.github.io
gergelyke.github.io copied to clipboard
Node.js Async Function Best Practices
@ksmithut thanks, fixed it!
async function main () {
const [user, product] = await Promise.all([
Users.fetch(userId),
Products.fetch(productId)
])
await makePurchase(user, product)
}
can also be written as
async function main () {
const user = Users.fetch(userId)
const product = Products.fetch(productId)
await makePurchase(await user, await product)
}
You do await + callbacks. "Best practices"? For real?
@slavaGanzin If you're referring to the express example, express uses callbacks exclusively, no way around it (ATM). So for express, yes, if that's what you're referring to.
@ksmithut No, I'm talking about last example from this article:
const util = require('util')
const async = require('async')
const numbers = [
1, 2, 3, 4, 5
]
mapLimitAsync = util.promisify(async.mapLimit)
async function main () {
return await mapLimitAsync(numbers, 2, (number, done) => {
setTimeout(function () {
done(null, number * 2)
}, 100)
})
}
main()
.then(console.log)
.catch(console.error)
Callbacks, promisified callbacks, await. This code is utter mess
The @sindresorhus promise-fun repo has a bunch of good promise helper modules, as an alternative to using the async module.