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

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

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

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 规范(当然更难阅读...):http://www.ecma-international.org/ecma-262/6.0/#sec-promise-executor

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天全站免登陆