据我所知,承诺是可以解决()或拒绝()的东西,但我很惊讶发现在调用解析或拒绝后,承诺中的代码继续执行 .
我认为解决或拒绝是退出或返回的异步友好版本,这将停止所有立即执行功能 .
有人可以解释为什么以下示例有时会在解析调用后显示console.log的想法:
var call = function() {
return new Promise(function(resolve, reject) {
resolve();
console.log("Doing more stuff, should not be visible after a resolve!");
});
};
call().then(function() {
console.log("resolved");
});
2 回答
JavaScript具有"run to completion"的概念 . 除非抛出错误,否则执行函数直到
return
语句或其结束 . 函数外部的其他代码不能干扰它(除非再次抛出错误) .如果您希望
resolve()
退出初始化函数,则必须通过return
前置它:当规范仍然需要异步调用时,将在
resolve
promise时调用的回调 . 这是为了确保在将promises用于混 Contract 步和异步操作时的一致行为 .因此,当您调用
resolve
时,回调会排队,并且函数会立即继续执行resolve()
调用之后的任何代码 .只有在给予JS事件循环后,才能将回调从队列中删除并实际调用 .