· This is the first day of my participation in Gwen Challenge. Please check the details: Gwen Challenge

Everyone knows that JavaScript is a single-threaded language. This means that only one thing can be done at a time, which can lead to blocking (for example, a dom node being removed internally by one application and needed by another thread, causing a collision). So how do we solve single-thread blocking? So you have an event loop.

So we all know that Javascript tasks are divided into synchronous tasks and asynchronous tasks (synchronous tasks — tasks that are executed immediately). Asynchronous tasks – Tasks that are executed asynchronously, such as Ajax requests, setTimeout timing functions, etc.). Different Task sources are assigned to different Task queues. Task sources can be divided into microtasks and macrotasks. In the ES6 specification, microtasks are called Jobs and MacroTasks are called tasks.

Common macro tasks: overall code, setTimeout, setInterval, setImmediate, I/O operations, postMessage, MessageChannel, UI rendering/UI events.

Common microtasks: New Promise(). Then, MutaionObserver(front-end backtracking), Object.observe (deprecated; Proxy object substitution), process.nexttick (Node.js).

So what is the execution flow of the event loop? The following figure

In the figure, we can see that the microtasks are executed between two macro tasks. After all the microtasks are executed, the main thread’s task queue will execute the next macro task. Based on the above macro and micro tasks we have such a topic for you, you can print your opinion of the output order in the comments.

    console.log("nihao");
    setTimeout(()=>{
        console.log("1");
    },0)
    new Promise((resolve)=>{
        console.log("promise");
        resolve()

    }).then(()=>{
        console.log("then");
    })
    console.log("3")
Copy the code

We can resolve this: when we encounter “console.log(“nihao”); Will print “nihao” directly. When a timer is encountered, a new macro task is created for later execution. When we encounter a promise, we simply execute the printed “promise” inside. When “3” is printed, it will print directly. At this point, we will go to the micro-task queue to check whether there are micro-tasks in this round, and find the callback function of THEN. Print “then” and then go to the macro task queue and print “1”. So I get nihao==>promise==>3==>then==>1. Did you get the answer right?