gergelyke.github.io icon indicating copy to clipboard operation
gergelyke.github.io copied to clipboard

Node.js Async Function Best Practices

Open gergelyke opened this issue 8 years ago • 6 comments

gergelyke avatar Oct 23 '17 03:10 gergelyke

@ksmithut thanks, fixed it!

gergelyke avatar Oct 25 '17 03:10 gergelyke

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)
}

xkizer avatar Oct 26 '17 14:10 xkizer

You do await + callbacks. "Best practices"? For real?

slavaGanzin avatar Oct 26 '17 20:10 slavaGanzin

@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 avatar Oct 26 '17 23:10 ksmithut

@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

slavaGanzin avatar Oct 30 '17 22:10 slavaGanzin

The @sindresorhus promise-fun repo has a bunch of good promise helper modules, as an alternative to using the async module.

https://github.com/sindresorhus/promise-fun

phelma avatar Nov 01 '17 12:11 phelma