JavaScript is single-threaded, so there is the concept of synchronous asynchrony, such as common setTimeout, Promise, wherein setTimeout is a macro task, Promise is a micro task.

Macro tasks include setInterval, and micro tasks include Node process.nextTick. Microtasks are less expensive than macro tasks.

*JS code execution sequence is that the code is executed according to the main thread. When encountering a macro task or micro task, it will not be executed immediately. Instead, it will queue up the macro task and micro task respectively, and then execute the main thread first.

What is the sequence between macro and micro tasks?

When the mainline code completes, the asynchronous task is executed. Whenever a macro task is executed, it is necessary to first check the microtask queue and execute the tasks in sequence, if any. When it’s done, the macro task is executed again and this is called an event loop.

Micro tasks can be added to a macro task. Just like when you do business in a bank, each person handling business is a macro task for the teller. A microtask is each small business (microtask) in a business (macro task) that everyone does. After finishing the savings business in front of you, you want to do financial management business, so your business needs to continue to be postponed. Whatever needs the teller can handle, they will do before dealing with your business. These can be considered microtasks. The next macro task will not be executed until the current micro task is complete.

Classic Interview questions

setTimeout (() => { console.log(4)})
new Promise (resolve => {
    resolve()
    console.log(1)
}).then (() => {
   console.log(3)
})
 console.log(2)
Copy the code

SetTimeout is a macro task, promise. then is a representative microtask, and the above code execution order is output in order. It prints 1234.

All of the asynchrony that will enter is that part of the code in the event callback.

That is, the code executed during the instantiation of a New Promise is synchronized, whereas the callbacks registered in then are executed asynchronously. Go back after the synchronous code has completed to check if any asynchronous tasks have completed and perform the corresponding callbacks, while the micro tasks are executed before the macro tasks.

Asyns /await functions

Because async/await is essentially based on some encapsulation of promises, which are a type of microtask. So using the await keyword has the same effect as promise.then:

setTimeout(_ =>console.log(4))

async function main() {
    console.log(1)  
    await Promise.resolve()
    console.log(3)
}
console.log(2)
Copy the code

Async code before await is executed synchronously. It can be understood that code before await belongs to code passed in newPromise, and all code after await is callback in promise.then.

Macro task

I/O, setTimeout, setInterval, setImmediate, requestAnimationFrame

Micro tasks

NextTick, MutationObserver, Promise. Then catch finally

demo

console.log('1'); SetTimeout (function() {// macro task console.log('2'); process.nextTick(function() { console.log('3'); }) new Promise(function(resolve) { console.log('4'); resolve(); }). Then (function() {console.log('5')})}) process.nexttick (function() {console.log('6'); }) new Promise(function(resolve) { console.log('7'); // macro task resolve(); }).then(function() {// console.log('8')})Copy the code

This code prints: 1 7 6 8 2 4 3 5

  1. First print 1. Go ahead and hit setTimeout and put it all in the macro task queue. Next, process.nextTick is placed on the microtask queue. And then print 7.

(Note that this is a function that executes immediately after a new Promise, not a microtask.) Then put the tasks after the then into the microtask queue. We now have setTimeout in the macro task queue and process.nextTick and then in the microtask queue.

  1. Continue, check the microtask queue before executing the macro task, and execute in sequence. Print: 6, 8.

  2. Ready to execute the macro task, setTimeout, print 2.

  3. Next, process. NextTick is encountered and placed on the microtask queue.

  4. Execute new Promise, print 4. Put then into the microtask. The microtask queue now contains process.nextTick and then

  5. Print 3 and 5 in sequence.