为什么JavaScript ES6 Promise在解决之后继续执行? [英] Why does javascript ES6 Promises continue execution after a resolve?

查看:1213
本文介绍了为什么JavaScript ES6 Promise在解决之后继续执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,承诺是可以解决()或reject()的,但是我很惊讶,发现承诺中的代码在解决或拒绝被调用后继续执行。



我认为解决或拒绝是一个异步友好版本的退出或返回,这将停止所有即时功能执行。



有人可以解释以下示例有时在解析调用后显示console.log:

  var call = function(){
返回新的承诺(功能(解决,拒绝){
resolve();
console.log(做更多的东西,在解决之后不应该可见);
} );
};

call()。then(function(){
console.log(resolved);
});

jsbin

解决方案

JavaScript的概念是运行到完成。除非发生错误,否则执行一个函数,直到返回语句或其结束为止。功能之外的其他代码不能干扰(除非再次出现错误)。



如果你想要 resolve() 退出您的初始化功能,您必须先通过返回

  return new Promise(function(resolve,reject){
return resolve();
console.log(在返回语句后不再做更多的东西);
});


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.

I considered resolve or reject being an async-friendly version of exit or return , that would halt all immediate function execution.

Can someone explain the thought behind why the following example sometimes shows the console.log after a resolve call:

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");
});

jsbin

解决方案

JavaScript has the concept of "run to completion". Unless an error is thrown, a function is executed until a return statement or its end is reached. Other code outside of the function can't interfere with that (unless, again, an error is thrown).

If you want resolve() to exit your initialiser function, you have to prepend it by return:

return new Promise(function(resolve, reject) {
    return resolve();
    console.log("Not doing more stuff after a return statement");
});

这篇关于为什么JavaScript ES6 Promise在解决之后继续执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆