preface
In JavaScript, tasks are divided into two types, oneMacro task (MacroTask)
, a kind ofMicro tasks (MicroTask)
-
Macro tasks: I/O, setTimeOut, setInterval, requestAnimationFrame
-
Microtasks: process.nextTick, Promise.then, catch, finally
JavaScript has the main thread and the call stack (execution stack), where all tasks are put and wait for the main thread to execute
Synchronous tasks and asynchronous tasks enter different task queues respectively. Synchronous tasks enter the main thread, and asynchronous tasks enter the Event Table and register functions.
After each macro task is executed, check whether the microtask queue is empty. If it is not empty, set the microtask queue to NULL after all the microtasks are executed according to the first-in, first-out rule. Then the macro task is executed, and so on.
The macro task is executed after the microtask (because the microtask is actually one of the steps of the macro task)
Important: Microtasks are executed in full, while macro tasks are executed one by one
Example analysis
Look at a piece of code
setTimeout(function() {
console.log('setTimeout');
})
new Promise(function(resolve) {
console.log('promise');
}).then(function() {
console.log('then');
})
console.log('console');
// promise console then setTimeout
Copy the code
-
Step 1: The code enters the main thread; When a setTimeout is encountered, register its callback function and distribute it to the macro task
-
Step 2: The incoming code executes immediately when a new Promise is generated, outputs the Promise, and then distributes it to the microtask
-
Step 3: Go ahead and print console
-
Step 4: The main thread execution stack has been emptied, execute all microtasks (fifO), print then
-
Step 5: after the execution of micro tasks is completed, find macro tasks (one by one), output setTimeout, and complete the whole execution
async/await
Async/await is essentially a wrapper based on promises, which are microtasks
The code before the async function await is executed synchronously. Code before await belongs to code passed in new Promise, and all code after await is callback in promise.then
reference
Learn the Event Loop once
Most complete HTTP request ever
Microtasks, macro tasks, and Event-loops