假设我有以下承诺:
function doSomethingAsynchronous() {
return new Promise((resolve) => {
const result = doSomeWork();
setTimeout(() => {
resolve(result);
}), 100);
});
}
在哪个时间点调用doSomeWork()?是在承诺之后还是在承诺之后?如果没有,是否还有一些我需要明确做的事情以确保Promise的主体运行?
解决方法:
立即,是的,按照规范.
从the MDN开始:
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
这种保证可能很重要,例如,当您准备好几个承诺,然后传递给全部或竞赛,或者执行者有同步副作用时.