2

The following code:

let promise = new Promise(function(resolve, reject) {
    console.log("resolve, reject are", resolve, reject);

    resolve("this is the success data");
    console.log("Point A");
    setTimeout(function() { console.log("Point B"); }, 0);
});

promise.then(
  function(a) { 
    console.log("Success.", a); 
    setTimeout(function() { console.log("Point C"); }, 0);
    promise.then(function(a) { console.log("Go have a drink.", a); });
  },
  function(a) { 
    console.log("failure", a) 
  }
);

console.log("Point D");

adds printing of "Point B" and "Point C" to the job queue, and after that, the handler that prints out "Go have a drink" is also added to the job queue. But "Go have a drink" is printed before "Point B" and "Point C" in the result in Node and in Google Chrome. Is it true that the promise has a separate job queue and the setTimeout and setInterval has a separate job queue, and the promise job queue is executed before the timed job queue? It seems the ES6 specs mentioned two job queues: ScriptJobs and PromiseJobs. Can we count on the promise job queue executed before the timed job queue?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

1 Answers1

3

Yes. Promise resolution handlers, like .then and await, are called microtasks. They will always execute immediately after all other synchronous Javascript currently running is finished.

Microtasks that other microtasks spawn will also run immediately (until all microtasks are completed, and nothing is left in the microtask queue).

Other examples of microtasks are process.nextTick and queueMicrotask.

In contrast, setTimeout callbacks are macrotasks, which run (at maximum) one every few milliseconds (during every iteration of the event queue), which is not instant.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thanks for the explanation. The ES6 specs mentioned ScriptJobs and PromiseJobs and not microtask and macrotask. So the whole PromiseJobs job queue is just full of microtasks? And the ScriptJobs job queue is full of macrotasks? – nonopolarity Dec 25 '19 at 10:13
  • 2
    Macrotasks and their APIs are handled by the implementation, like the browser - their behavior isn't specified in the ECMAScript standard itself. Microtasks, on the other hand, can be: see [Jobs and Job Queues](https://tc39.es/ecma262/#sec-jobs-and-job-queues): *Execution of a Job can be initiated only when there is no running execution context and the execution context stack is empty. A PendingJob is a request for the future execution of a Job.* – CertainPerformance Dec 25 '19 at 11:18
  • Queued ScriptJobs run as soon as the job stack is empty - they're microtasks too, just like `.then`s. – CertainPerformance Dec 25 '19 at 11:19