Why does javascript ES6 Promises continue execution after a resolve?

◇◆丶佛笑我妖孽 提交于 2019-11-28 16:28:18
Felix Kling

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

The callbacks that will be invoked when you resolve a 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.

Therefore when you invoke resolve the callback is queued, and function execution continues immediately with any code following the resolve() call.

Only once the JS event loop is given back control can the callback be removed from the queue and actually invoked.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!