javascript - javascript async/await 是如何工作的?

标签 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");

根据official document关于异步/等待:

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.

我希望得到以下输出:

dosomething1
//wait for 6 seconds
dosomething2
Promise { <state>: "fulfilled", <value>: "returnfromfun1" }
hello

但实际输出是:

dosomething1
Promise { <state>: "pending" }
hello
//wait for 6 seconds
dosomething2

似乎 fun1 在“await”行返回。是不是我理解错了官方文档中的描述?而且我似乎从来没有得到 fun1("returnfromfun1") 的返回值。

最佳答案

你必须稍微不同地阅读引用的部分:

An async function can contain an await expression that pauses the execution of the async function

只有异步函数本身会暂停执行,调用它的函数会继续执行。

如果您想到一个同步调用堆栈,就会发生异步函数上下文被弹出并存储在其他地方的情况:

 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

是的,没错。在那一刻它返回一个 promise ,当异步函数返回时解决(在它继续执行之后的某个时候)。

And it seems I never get the return value of fun1("returnfromfun1").

你可以在 promise resolve 时得到它:

  fun1().then(result => console.log(result));

关于javascript - javascript async/await 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57160341/

相关文章:

javascript - 如何使用带有 location.reload 方法的 Javascript 控制 F5

javascript - 如何获取 html 输入的值并执行 google 搜索?

javascript - 为什么我不能放入 Promise.catch 处理程序?

c# - 如何合并多个异步调用的结果

c# - 在异步/等待代码中重新分配 Transaction.Current 时上下文丢失

stream - Dart 中等待和聆听的区别

javascript - TypedArray 集合与展开循环 (Javascript)

javascript - 自动计算动态文本框值的总和

javascript - 多次异步调用后的回调方法

javascript - 如何使用 axios 获取/发布?