Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

They're all artificial examples: one could assume that the tasks in #3 are intended to be executed serially. Though there aren't any data dependencies expressed between the different calls, perhaps ordering could be important for other reasons.


I feel it should have been called out explicitly when introducing await, because the 'clean' solution in async/await code is to call each async function and then await the results where you need them - which is a pattern he doesn't hint at at all.


I think there is a danger in that approach: if you forget to await, errors are silently ignored. You can also await a Promise.all, which is reasonably good enough if you do depend on all of the results to do anything meaningful anyways.


If you need you can name your intermediate results fooPromise or something else to make it obvious that it isn't meant to be used directly.

The async article linked from this article has a toy example for this concept where the result is unused, but most of the time you would be passing the result somewhere. If you were using typescript it could fail at compile time when you try to pass a promise instead of the expected type. Even if you're not, you should notice it never work in your tests.


Sorry, by forget to await, I mean you call an async function but then don’t ever actually use the result. TypeScript can also diagnose that one by illuminating unused variables.

Still, I think it is easiest to never mess up if you await as soon as you have a promise value. In many common cases this is easy enough.


A bigger danger still would be:

  const userPromise = fetchUser(id)
  const itemPromise = fetchItem(itemId)
  // Do stuff, maybe even more async stuff
  const item = await itemPromise
  const user = await userPromise
Since those promises haven't been awaited until later in the code, they could throw and result in an unhandledRejection, which would be pretty bad. Promise.all is much safer since it instantly awaits both promises.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: