Search code examples
javascriptpromisesettimeoutv8

When are promises no longer prioritized?


Why is setTimout() prioritized before promises? Please have a look at the two examples below. Based on my knowledge, Promises are prioritized, in other words, Promises will be executed before setTimeout(). And that is proven in the first example below.

console.log("First");

setTimeout(() => console.log("Second"), 0);

console.log("Third");

const promise = new Promise(function (resolve, reject) {
      resolve("Forth");
      reject(new Error("Rejected"));
});
promise.then((res) => console.log(res)).catch((err) => console.log(err));
//output:

//"First"
//"Third"
//"Forth"
//"Second"

BUT if we have a setTimeout() inside a promise, it will no longer be prioritized. Is it no longer a promise? Why does it behave this way? Shouldn't the second example have the same output as the first one?

console.log("First");

setTimeout(() => console.log("Second"), 0);

console.log("Third");

const promise = new Promise(function (resolve, reject) {
  setTimeout(function () {
    resolve("Forth");
    reject(new Error("Rejected"));
  }, 0);
});
promise.then((res) => console.log(res)).catch((err) => console.log(err));

//"First"
//"Third"
//"Second"
//"Forth"

Solution

  • setTimeout has a minimum time out period which means it means it will:

    • always come after a promise that has resolved immediately.
    • cause resolve, in your second example, to be called a moment after the first timeout has triggered console.log.