javascript - 在等待 JavaScript 中的 promise 时到底发生了什么?

标签 javascript promise async-await

我在文档或相关资源中似乎找不到的一点是,当 JS 命中 await 关键字时,关于调用函数和事件循环的过程是什么。

这是 specs 的内容状态:

The await expression causes async function execution to pause until a Promise is resolved, that is fulfilled or rejected, and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise.

这一切都说得通,但暂停的真正含义是什么?该函数是否立即返回给调用者,然后当等待的 promise 解决时,它和异步方法的其余部分被添加到微任务队列中进行处理?我知道 async/await 是 Promise API 的语法糖,所以我假设这就是发生的事情,但我想确保我真的理解发生的“魔法”当到达 await 时。

根据我的阅读,这似乎是在 C# 中完成的,但我不确定它是如何转换为 JS 的。

最佳答案

就是你说的,把剩下的函数放到一个微任务Q里面,然后返回main函数。

然后当 promise resolve 时,它​​会执行异步部分。

帮助我理解它的是将 async/await 转换为 promise 语法,然后它就变得清晰了。

例如:

async function doSomthing() {
  someSync();

  const result1 = await someAsync();
  const result2 = await someAsync2();

  return result1 + result2;
}

“转换”为:

function doSomthing() {
  someSync();

  return someAsync().then(result1 => {
    return someAsync2().then(result2 => {
      return result1 + result2;
    });
  });
}

您可以看到 doSomthing 立即返回 promise 。

关于javascript - 在等待 JavaScript 中的 promise 时到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56323837/

相关文章:

node.js - 在 express 发送错误时防止代码重复的最有效方法

c# - 在 ContinueWith block 内使用 await 的意外行为

php - 提交前验证表单

java - 在 netty 4.1 中如何在没有 channel 的情况下新建一个 promise

javascript - 将钩子(Hook)应用于某些路由 Node.js

javascript - JQuery AjaxSetup BeforeSend Promise

javascript - 异步/等待 vs 组合生成器和 promise ?

Dart 流,相当于 await for

javascript - querySelectorAll 包含 self

javascript - 使用 Rails 和 Haml 的 Jquery 和 CoffeeScript scrollTo