Why does javascript ES6 Promises continue execution after a resolve?

后端 未结 2 692
-上瘾入骨i
-上瘾入骨i 2020-12-07 11:46

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

2条回答
  •  我在风中等你
    2020-12-07 12:49

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

提交回复
热议问题