且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Promise 构造函数回调是否异步执行?

更新时间:2022-06-06 00:15:56

这取决于承诺的实现.如果我们检查规范.您可以在 此处 找到最终规范 - 由于此答案最初是编写的,因此已经敲定.

It depends on the implementation of the promise. If we check the spec. You can find the final spec here - since this answer was originally written, it has been finalized.

这是相关的摘录(你可以找到原始来源这里)

Here is the relevant excerpt (you can find the original source here)

  1. 让完成成为 Call(executor, undefined, «resolvingFunctions.[[Resolve]],resolutionFunctions.[[Reject]]»).
  2. 如果完成是一个突然的完成,那么
    • 让状态为 Call(resolvingFunctions.[[Reject]], undefined, «completion.[[value]]»).
    • ReturnIfAbrupt(状态).

ES6 标准表明承诺的履行是总是异步的(参见第 25.4.5.3 节,Promise.prototype.then 和随附的第 25.4.5.3.1 节, PerformPromiseThen).我已经把相关材料放在下面了.

The ES6 standard indicates that the fulfillment of a promise is always asynchronous (See section 25.4.5.3, Promise.prototype.then and accompanying section 25.4.5.3.1, PerformPromiseThen). I have placed the relevant material below.

  1. 否则,如果 promise 的 [[PromiseState]] 内部槽的值为已完成",
    • 令 value 为 promise 的 [[PromiseResult]] 内部槽的值.
    • 执行 EnqueueJob("PromiseJobs", PromiseReactionJob, «fulfillReaction, value»).
  • 让reason 成为promise 的[[PromiseResult]] 内部槽的值.
  • 执行 EnqueueJob("PromiseJobs", PromiseReactionJob, «rejectReaction, reason»).

TLDR:传递给promise的函数是同步执行的,但是后续的then调用总是异步执行的.

TLDR: the function passed to the promise is executed synchronously, but subsequent then calls are always executed asynchronously.