JS async await execution process
Example
console.log("0")
async function f() {
console.log("1");
const pr1 = await new Promise((resolve) => {
console.log("2");
setTimeout(() => {
console.log("3");
resolve("pr1");
}, 5000);
});
const pr2 = await new Promise((resolve) => {
console.log("4");
setTimeout(() => {
console.log("5");
resolve("pr2");
}, 2000);
});
return [pr1, pr2];
}
console.log("6");
f().then(result => console.log("Result:", result));
console.log("7");
==========OUTPUT==========
0
6
1
2
7
3 (after 5 seconds)
4
5 (after 2 seconds)
Result: [pr1, pr2]
Execution order
-
console.log("0")0 -
async function f()is just declared. Nothing runs yet. -
console.log("6")6 -
f()is called.-
console.log("1") - First promise is created.
- Executor of the promise runs immediately.
-
console.log("2") -
setTimeout(..., 5000)is scheduled. -
Execution pauses at the first
await.
Output so far:
0 6 1 2 -
- Control returns to the caller.
-
console.log("7")7 -
After 5 seconds, the first timer fires.
3The first promise resolves, so the async function resumes in a microtask.
-
Execution continues after the first
await.- Second promise is created.
- Executor runs immediately.
4-
setTimeout(..., 2000)is scheduled. -
Execution pauses at the second
await.
-
After 2 more seconds, the second timer fires.
5The second promise resolves, so the async function resumes, returns:
["pr1", "pr2"] -
The
.then()callback runs as a microtask.Result: [ 'pr1', 'pr2' ](Exact formatting depends on the JavaScript environment.)
Comments
Post a Comment