Promise 构造函数回调是否异步执行? [英] Is the Promise constructor callback executed asynchronously?

查看:24
本文介绍了Promise 构造函数回调是否异步执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个代码

function y(resolve, reject)
{
  console.log("Result");
  resolve();
}  

var promise = new Promise(y);

我想知道函数y是否会异步执行.

What I want to know is whether the function y will be executed asynchronously or not.

推荐答案

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

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.

这篇关于Promise 构造函数回调是否异步执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆