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

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

问题描述

据我所知,promise 是可以 resolve() 或 reject() 的东西,但我惊讶地发现 promise 中的代码在调用 resolve 或 reject 后继续执行.

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.

我认为 resolve 或 reject 是 exit 或 return 的异步友好版本,这将停止所有立即函数执行.

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

有人可以解释为什么以下示例有时会在解析调用后显示 console.log 背后的想法:

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 有 运行完成".除非抛出错误,否则函数将一直执行,直到到达 return 语句或其结尾.函数之外的其他代码不能干扰它(除非再次抛出错误).

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).

如果你想让 resolve() 退出你的初始化函数,你必须在它前面加上 return:

If you want resolve() to exit your initializer 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 Promises 在解析后继续执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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