It'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.
That'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.
Re:Mistakes we make using JavaScript Promises
by Nullabillity on Friday July 05, 2019 @12:29PM
(#20363741)
Promises 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()]);
Re:Mistakes we make using JavaScript Promises
by pault on Tuesday July 09, 2019 @03:49PM
(#20395850)
Whoops, you're right! I hadn't thought it through.
Re:Mistakes we make using JavaScript Promises
by smusumeche on Friday July 05, 2019 @12:45AM
(#20359904)
TypeScript helps immensely in this case.
Re:Mistakes we make using JavaScript Promises
by matt-attack on Friday July 05, 2019 @10:01AM
(#20362551)
Also 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.
For the first I wonder if we could solve this with array syntax:
const [foo, bar] = await [async1(), async2()]
Re:Mistakes we make using JavaScript Promises
by simplify on Friday July 05, 2019 @01:23AM
(#20360038)
Yes, the correct syntax is:
const [foo, bar] = await Promise.all([async1(), async2()])
Re:Mistakes we make using JavaScript Promises
by ailideex on Friday July 05, 2019 @12:45AM
(#20359907)
You can use await on the promise returned by Promise.all()
Re:Mistakes we make using JavaScript Promises
by panopticon on Friday July 05, 2019 @12:03AM
(#20359744)
I'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...
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.