问题
I have some code using javascript async/await:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fun1()
{
console.log("dosomething1");
await sleep(6000);
console.log("dosomething2");
return "returnfromfun1";
}
console.log(fun1());
console.log("hello");
According to the official document about async/await:
An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.
I expect the following output:
dosomething1
//wait for 6 seconds
dosomething2
Promise { <state>: "fulfilled", <value>: "returnfromfun1" }
hello
But the actual output is:
dosomething1
Promise { <state>: "pending" }
hello
//wait for 6 seconds
dosomething2
It seems fun1 returns at the "await" line. Did I misunderstand the description in the official document? And it seems I never get the return value of fun1("returnfromfun1").
回答1:
You have to read the quoted part slightly differently:
An async function can contain an await expression that pauses the execution of the async function
Just the async function itself pauses execution, the function that called it goes on then.
If you think of a synchronous callstack, what happens is that the asynchronous functions context gets popped of, and stored somewhere else:
stack: [init] -> [async] fun1 -> sleep -> setTimeout
// The promise gets returned from sleep
stack: [init] -> [async] fun1
// The async function gets popped of
stack: [init]
hidden: [async] fun1
// synchronous execution ends
stack: -
hidden: [async] fun1
// the timer triggers, the promise gets resolved
stack: setTimeout callback
hidden: [async] fun1
// synchronous execution ends
stack: -
hidden: [async] fun1
// the promise resolves, the async fun1 context gets moved onto the stack
stack: [async] fun1
It seems fun1 returns at the "await" line
Yes, exactly. In that moment it returns a promise, that resolves when the async function returns (after it continued execution somewhen).
And it seems I never get the return value of fun1("returnfromfun1").
You can get it when the promise resolves:
fun1().then(result => console.log(result));
来源:https://stackoverflow.com/questions/57160341/how-does-javascript-async-await-actually-work