Promise 的主体何时执行?

新手上路,请多包涵

假设我有以下 Promise

 function doSomethingAsynchronous() {
  return new Promise((resolve) => {
    const result = doSomeWork();

    setTimeout(() => {
      resolve(result);
   }), 100);
  });
}

在哪个时间点调用 doSomeWork() ?它是在构建 Promise 之后还是构建时立即构建的?如果没有,我是否需要明确地做一些额外的事情来确保 Promise 的主体运行?

原文由 Kevin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 599
2 个回答

立即,是的,根据规范。

来自 MDN

执行器函数由 Promise 实现立即执行,传递 resolve 和 reject 函数(执行器在 Promise 构造函数甚至返回创建的对象之前被调用)

这是在 ECMAScript 规范中定义的(当然,它更难阅读……) 此处(此编辑的第 9 步,显示执行程序被同步调用):

  1. 设完成为 Completion( Call(executor, undefined, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] ») )

(我的重点)

这种保证可能很重要,例如,当您准备多个承诺时,然后传递给 allrace ,或者当您的执行者具有同步副作用时。

原文由 Denys Séguret 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以从下面看到,只需将同步代码放入主体而不是异步代码,主体就会立即执行:

 function doSomethingAsynchronous() {
  return new Promise((resolve) => {
    console.log("a");
    resolve("promise result");
  });
}
doSomethingAsynchronous();
console.log("b");

结果显示 promise 正文立即执行(在打印 ‘b’ 之前)。

Promise 的结果被保留,将被释放到“then”调用,例如:

 function doSomethingAsynchronous() {
  return new Promise((resolve) => {
    console.log("a");
    resolve("promise result");
  });
}

doSomethingAsynchronous().then(function(pr) {
  console.log("c:" + pr);
});
console.log("b");

结果:

 a
b
c:promise result

与正文中的异步代码处理相同,除了在实现承诺之前的不确定延迟和可以调用“then”(点 c )。 So a and b would be printed as soon as doSomethingAsynchronous() returns but c appears only when the promise is fulfilled (‘resolve’ is称为)。

一旦添加了对 then 的调用,表面上看起来很奇怪的是 b 打印在 c 之前,即使一切都是同步的。

当然 a 会打印,然后 c 最后 b

The reason why a , b and c are printed in that order is because no matter whether code in the body is async or syncthen 方法总是由 Promise 异步调用。

In my mind, I imagine the then method being invoked by something like setTimeout(()=>{then(pr)},0) in the Promise once resolve is called.也就是说,当前执行路径必须在传递给 then 的函数被执行之前完成。

Promise 规范中不明显 为什么要这样做?

我的猜测是它确保了关于何时调用 then 一致行为(总是在当前执行线程完成之后),这大概是为了允许多个 Promises 在开始所有之前被堆叠/链接在一起 then 连续调用。

原文由 Moika Turns 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题