Promise的主体何时执行? [英] When is the body of a Promise executed?

查看:275
本文介绍了Promise的主体何时执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下Promise:

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

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

在什么时间调用doSomeWork()?它是在紧随Promise之后还是在构建之后?如果没有,我还需要做其他一些事情来确保Promise的主体运行吗?

At which point in time is doSomeWork() called? Is it immediately after or as the Promise is constructed? If not, is there something additional I need to do explicitly to make sure the body of the Promise is run?

推荐答案

立即,按规范.

来自 MDN :

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

The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object)

此处包含在ECMAScript规范中(当然更难阅读...):

Here it is in the ECMAScript specification (of course harder to read...): http://www.ecma-international.org/ecma-262/6.0/#sec-promise-executor

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

This guarantee may be important, for example when you're preparing several promises you then pass to all or race, or when your executors have synchronous side effects.

这篇关于Promise的主体何时执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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