Reputation: 55
Hi everyone i hope you guys doing well and sorry for the stupid question, I just wondering does async/await allow other tasks to run?.
I just read the downside of async await on MDN and there is a part that says "it does allow other tasks to continue to run in the meantime, but your own code is blocked." what does it mean by that? and is it only async/await can allow other tasks to run or can promises do that too? if so can you guys give me examples please? thank you in advance :)
Upvotes: 3
Views: 1478
Reputation: 943569
When a function hits an await
statement, it runs the code on the right-hand-side to get the promise and then goes to sleep.
Other functions can run in the meantime, but any further lines in this one won't until the promise resolves.
That isn't a downside. That's the point.
async function example() {
const result = await somethingFromAPromise();
do_something_with(result);
}
If it didn't stop, then you wouldn't have the result
to do something with on the next line.
What that section of documentation is saying, in a very long winded way, is that sometimes you'll have a situation like this:
async function example() {
const result1 = await somethingFromAPromise();
const result2 = await somethingFromAnotherPromise();
do_something_with(resul1, result2);
}
… where you have two promises that could run in parallel because they are completely independant, but you don't start the second one until the first one is finished.
It also tells you how to mitigate that
async function example() {
const result1Promise = somethingFromAPromise();
const result2Promise = somethingFromAnotherPromise();
const [result1, result2] = await Promise.all(result1Promise, result2Promise);
do_something_with(resul1, result2);
}
Upvotes: 8