Callback function and setTimeout execution order in Promise's then method

  setTimeout(function(){
        console.log("D");
    },0)

    var promise = new Promise(function(resolve, reject){
        console.log("A");
        resolve("C");
    })

    console.log("B");
    
      promise.then(function(value){
        console.log(value)
    });
    
    ABCDsetTimeout
Mar.31,2021

this involves asynchronous macro tasks and micro tasks. SetTimeout is a macro task, and Promise as a whole is a micro task. After the main thread finishes execution, it first gets the micro task execution from the micro task stack. If there is no micro task, it goes to the macro task stack to get macro task execution. So in a cycle, the micro task is executed before the macro task, so print C first and then print D


.

because there are two queues.

one is a microtask queue and one is a macrotask queue.

promise is placed in the microtask queue, while setTimeout is placed in the macrotask queue.

first deal with microtask queues. Microtask queues are processed each time until the queues are empty, and then macrotask queues are processed. Macrotask only deals with the first task in the queue each time. When the task is finished, it will enter the processing of microtask queues. Over and over again.


this is easy to understand, and basically lies in a clear understanding of the asynchronous problem.

first of all, you are right about setTimeout. It is a queue execution. There are many other things similar to setTimeout, such as
setImmediate, process.nextTick in node, which are similar mechanisms.
these functions are executed with a delay, which, as the name implies, is to be queued, even if the delay is set to 0.

but what is Promise?
in a nutshell, it's just an asynchronous programming solution. To put it bluntly, it's a problem of changing the way callback functions are written before. A Promise, is simply a container that holds the result of an event (usually an asynchronous operation) that ends in the future. The stored queue is the own queue maintained by promsie itself, and should not be confused with the setTimeout system event scheduling queue.

for your problem, your promise is not asynchronous, so the state of promsie immediately becomes resolve, so the callback function registered through then will be called immediately. Basically, it's just Synchronize implementation. Of course, it was executed before setTimeout.


setTimeout(function(){console.log(4)},100); 
new Promise(function(resolve){ 
    console.log(1) 
    setTimeout(()=>{console.log('x');resolve();},0) 
    console.log(2) })
.then(function(){ console.log(5) }).then(()=>{for(let i=0;i<1000;iPP){}console.log(6)});
 console.log(3);

then is executed immediately after resolve, so the execution order of then and settimeout is actually the order of resolve and setTimeout. I wonder if this is correct?

Menu