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

查看:79
本文介绍了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.

推荐答案

这取决于promise的实现。如果我们查看规范。您可以在此处找到最终规范-由于此答案最初是撰写的,因此,已经完成。

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(执行程序,未定义,«resolvingFunctions。[[Resolve]],resolvevingFunctions。[[Reject]]»)。

  2. 如果完成是突然完成,则


    • 让状态为Call(resolvingFunctions。[[Reject]],未定义,«completion。[[value]]»)。

    • ReturnIfAbrupt(status)。

ES6标准指出承诺的兑现总是异步的(请参见第25.4.5.3节 Promise.prototype.then 和相应的第25.4.5.3.1节, PerformPromiseT母鸡)。我将相关材料放在下面。

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]]内部插槽的值已实现,则


    • 让值成为promise的[[PromiseResult]]内部的值

    • 执行EnqueueJob( PromiseJobs,PromiseReactionJob,«fulfillReaction,value»)。


  • 让原因是promise的[[PromiseResult]]的值

  • 执行EnqueueJob( PromiseJobs,PromiseReactionJob,«rejectReaction,reason»)。

TLDR :传递给promise的函数是同步执行的,但随后的然后调用总是异步执行。

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

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

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