Why does javascript ES6 Promises continue execution after a resolve?

Ludwig Van Beethoven picture Ludwig Van Beethoven · Mar 6, 2015 · Viewed 29.1k times · Source

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

Answer

Felix Kling picture Felix Kling · Mar 6, 2015

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