Home  >  Q&A  >  body text

javascript - Confusion about the execution order of promise and setTimeout

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?

高洛峰高洛峰2673 days ago1121

reply all(3)I'll reply

  • 黄舟

    黄舟2017-06-26 10:59:47

    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

    reply
    0
  • 某草草

    某草草2017-06-26 10:59:47

    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

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-06-26 10:59:47

    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.

    reply
    0
  • Cancelreply