The problem with the execution order of promise and setTimeout

Welcome to my personal blog: http://www.xiaolongwu.cn

foreword

Promise is a language standard introduced by es6, a solution for asynchronous programming;

The premise of reading this article is to understand the basic usage and characteristics of promises, such as his self-execution characteristics, state irreversible characteristics, etc.

throw questions

Let's look at the code and the problem below

setTimeout(function(){console.log(1)},0);
new Promise(function(resolve){
console.log(2)
for( var i=0 ; i<10000 ; i++ ){
i==9999 && resolve()
}
console.log(3)
}).then(function(){
console.log(4)
});
console.log(5);
// 这的问题是,为什么答案是 2 3 5 4 1
// 而不是 2 3 5 1 4

Since both promise.then and setTimeout are asynchronous, the event of promise.then should be queued after setTimeout in the event loop queue, so why is promise.then printed before setTimeout?

Answer

This is how I understand this problem. The browser reads the code in the script tag is also an event queue, the task of Promise will be executed at the end of the current event loop, and the task in setTimeout is executed in the next event loop

image

The picture above shows the contents of Chapter 1, Section 5 of the second part of the volume of "JavaScript You Don't Know"

github resource address: https://github.com/promise and setTimeout execution order problem.md

My personal blog: http://www.xiaolongwu.cn

csdn blog address: https://blog.csdn.net/wxl1555

If you have any doubts or questions about the content of my blog, please leave a message in the comment area below, or email me to learn and progress together.

Email: [email protected]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324774175&siteId=291194637