4 ms·
async/await helps a lot, but there are still a few common errors with them... 1) Not calling promises in parallel. Easy to do because it's impossible to run th
by paulhodge 7y ago
async/await helps a lot, but there are still a few common errors with them...
1) Not calling promises in parallel. Easy to do because it's impossible to run them in parallel with just "await", need to use Promise.all() or something.
2) Forgetting to write "await". If you try to use the return value then now you have a Promise object instead of the actual value. But the worst is when the code doesn't use the return value. Then it has a really subtle race condition that's hard to find. Or if the promise has any errors, then you might get the dreaded "Unhandled promise rejection" with a useless stack trace, and you might need to search the entire codebase to find where it happened.
- panopticon 7y agoI've seen a lot of developers at the place I work make the mistake you outline in #1. Always something I'm watching out for in code reviews...
- ng12 7y agoFor the first I wonder if we could solve this with array syntax: const [foo, bar] = await [async1(), async2()]
- smusumeche 7y agoTypeScript helps immensely in this case.
- peq 7y agoIt's easy to run tasks in parallel with just "await". Just start your tasks without await, store the promise in a variable, and then use await later when you actually need the value.
- pault 7y agoThat's fine, but you'll still only be able to block on one promise at a time. If you want to wait until all promises have resolved you still have to use Promise. all.
- Nullabillity 7y agoPromises are started eagerly, so const xP = getX(); const yP = getY(); const x = await xP; const y = await yP; is just as parallel as const [x, y] = Promise.all([getX(), getY()]);
- pault 7y agoWhoops, you're right! I hadn't thought it through.
- matt-attack 7y agoAlso sometime I don’t want promise.all but I do want them in parallel somewhat but with a max concurrency setting. Still have to pull out the old async.js package for that one and use it’s maxLimit.