I just started learning async-await and just want to know the program execution flow clearly.
async function A() {
await doSomethingAsync();
doThisNext();
}
A();
B();
C();
Given that above code snippet, let's say B() is being executed at the moment.
While B() is executing and if doSomethingAsync() gets resolved right at that moment, will the programing execution suspends B() temporarily to resume A() (ie; start doThisNext() and then switch back?
Or will B() (or even C()) be finished up first and then executes doThisNext()?
Or I am misunderstanding the whole thing?
Assume B and C are just generic functions with no async code.
While B() is executing and if doSomethingAsync() gets resolved right at that moment, will the programing execution suspends B() temporarily to resume A() (ie; start doThisNext() and then switch back?
This is not how event loop works. If B is synchronous it wont be interrupted by promise resolution. Which is scheduled to be executed during current promise resolution micro-queue.
So, the order will be
A();
B();
C();
async function A() {
console.log('A start');
await delay(0);
// or even
// await Promise.resolve('done')
console.log('A end')
}
function B() {
console.log('B')
}
function C() {
console.log('C')
}
function delay(ms) {
return new Promise(r => setTimeout(r, ms))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With