Promise的主体何时执行? [英] When is the body of a Promise executed?
问题描述
假设我有以下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
此保证可能很重要,例如,当您准备几个承诺然后传递给all
或race
时,或者当执行者具有同步的副作用时.
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屋!