javascript - Confusion about the execution order of promise and setTimeout
高洛峰
高洛峰 2017-06-26 10:57:47
0
3
1165
setTimeout(function () {
    console.log(1)
}, 0);
new Promise(function executor(resolve) {
        resolve();
}).then(function () {
    console.log(2);
});

With the above code, why is the result 2,1 instead of 1,2?
Isn’t setTimeout added to the task queue first?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
黄舟

In terms of specifications, setTimeout has a minimum time of 4ms, which means that no matter how much you set, there must be at least an interval of 4ms before running the callback inside it (of course, whether the browser follows this specification is another story) thing). The asynchrony of Promise does not have this problem.

In terms of specific implementation, the two asynchronous queues are different. The asynchronous queue where Promise is located has a higher priority.
For details, you can read this article: Looking at Event Loop, Tasks and Microtasks in JavaScript from Promise

某草草

The tasks in

Promise will be executed at the end of the current event loop, while the tasks in setTimeout will be executed in the next event loop

淡淡烟草味

I suggest you read it, and then you will understand the content around section 1.5 in "JS You Don't Know (Volume 2)". That's what I understood after reading it before.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template