Wil*_*iam 6 javascript asynchronous async-await
我有一些使用 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");
Run Code Online (Sandbox Code Playgroud)
根据官方文档关于async/await:
异步函数可以包含await 表达式,该表达式暂停异步函数的执行并等待传递的Promise 的解析,然后恢复异步函数的执行并返回解析的值。
我期望以下输出:
dosomething1
//wait for 6 seconds
dosomething2
Promise { <state>: "fulfilled", <value>: "returnfromfun1" }
hello
Run Code Online (Sandbox Code Playgroud)
但实际输出是:
dosomething1
Promise { <state>: "pending" }
hello
//wait for 6 seconds
dosomething2
Run Code Online (Sandbox Code Playgroud)
看起来 fun1 在“await”行返回。难道我对官方文档的描述有误解?看来我从来没有得到 fun1("returnfromfun1") 的返回值。
您必须以稍微不同的方式阅读引用的部分:
异步函数可以包含暂停异步函数执行的await 表达式
只是异步函数本身暂停执行,调用它的函数然后继续执行。
如果您考虑同步调用堆栈,则会发生异步函数上下文被弹出并存储在其他地方的情况:
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
Run Code Online (Sandbox Code Playgroud)
看来 fun1 在“await”行返回
对,就是这样。在那一刻,它返回一个承诺,当异步函数返回时(在它继续执行之后)。
看来我从来没有得到 fun1("returnfromfun1") 的返回值。
当 Promise 解决时你就可以得到它:
fun1().then(result => console.log(result));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1989 次 |
| 最近记录: |