Javascript 为什么javascript ES6 Promises 在解析后继续执行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28896280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does javascript ES6 Promises continue execution after a resolve?
提问by Ludwig Van Beethoven
As I understand a promise is something that can resolve() or reject() but I was suprised to find out that code in the promise continues to execute after a resolve or reject is called.
据我所知,promise 是可以 resolve() 或 reject() 的东西,但我很惊讶地发现在调用 resolve 或 reject 后,promise 中的代码继续执行。
I considered resolve or reject being an async-friendly version of exit or return , that would halt all immediate function execution.
我认为 resolve 或 reject 是 exit 或 return 的异步友好版本,这将停止所有立即函数执行。
Can someone explain the thought behind why the following example sometimes shows the console.log after a resolve call:
有人可以解释为什么以下示例有时会在解析调用后显示 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");
});
回答by Felix Kling
JavaScript has the concept of "run to completion". Unless an error is thrown, a function is executed until a returnstatement or its end is reached. Other code outside of the function can't interfere with that (unless, again, an error is thrown).
JavaScript 有“运行到完成”的概念。除非抛出错误,否则函数将一直执行,直到return到达语句或其结尾。函数之外的其他代码不能干扰它(除非再次抛出错误)。
If you want resolve()to exit your initialiser function, you have to prepend it by return:
如果你想resolve()退出你的初始化函数,你必须在它前面加上return:
return new Promise(function(resolve, reject) {
return resolve();
console.log("Not doing more stuff after a return statement");
});
回答by Alnitak
The callbacks that will be invoked when you resolvea promise are still required by the specification to be called asynchronously. This is to ensure consistent behaviour when using promises for a mix of synchronous and asynchronous actions.
resolve规范仍然要求异步调用承诺时将调用的回调。这是为了确保在将 Promise 用于同步和异步操作的混合时的一致行为。
Therefore when you invoke resolvethe callback is queued, and function execution continues immediately with any code following the resolve()call.
因此,当您调用resolvecallback is queued 时,函数会立即继续执行调用后的任何代码resolve()。
Only once the JS event loop is given back control can the callback be removed from the queue and actually invoked.
只有一旦 JS 事件循环被重新控制,回调才能从队列中移除并实际调用。

