I. Event Loop of initial understanding
In fact, when it comes to task queues, the first thing most people think of is synchronous/asynchronous, macro/micro tasks, as well as many blogs and posts detailing them. After watching the course Relearning front-end in Geek time taught by Teacher Winter, I found that I didn’t know enough about Event Loop, so I started with a topic:
// Write out the output order
function sleep(duration) {
return new Promise(function(resolve, reject) {
console.log("b");
setTimeout(resolve,duration); })}console.log("a");
sleep(5000).then(() = >console.log("c"));
Copy the code
Ok, this seems pretty simple, and most people will come up with a sequence of events (synchronous -> microtasks -> macro tasks) :
Script start -> Promise immediately executes the function -> Promise then function -> setTimeout
The answer is this:
1. a // Synchronize execution
2. b // Promise internally executes functions immediately (sync)
3. c // Asynchronous task (microtask, asynchronous execution)
Copy the code
In fact, although the answer is correct, this is the wrong order of execution. The correct order of execution is:
Script start -> Promise immediately executes the function -> setTimeout -> Promise then function
amazing! Why is there microtask execution following macro task execution? Take it easy. Look down carefully.
Real Event Loop
One of the features of JavaScript language is single threading. Multiple tasks need to be executed in a certain order, and this rule is our Event Loop mechanism, which can be called Event Loop in Node.
To see the event loop again:
A Macro Task contains a queue of Micro tasks. The Macro Task contains a queue of Micro tasks.
So we can summarize the general steps to solve the event loop problem:
- Determine the number of macro tasks;
- Determine the number and call order of micro tasks in macro tasks;
- Determine the call order of macro tasks;
Looking back at the question above, is it clear:
- Synchronous execution
console.log("a")
; - Synchronous execution
console.log("b")
; - SetTimeout “enter” the macro task queue;
- Since resolve() is not called by Promise, there is no microtask in the script macro task and execution is complete.
- The setTimeout macro task executes, resolve is called, and the then function enters the microtask queue.
- Execute the Promise then function,
console.log("c")
;
Three, draw inferences
In fact, Event Loop is a very basic level that students must pass during the interview. Actually, it is only simple to understand. If the knowledge of Event Loop and Promise is combined, a search on Baidu will often find many interview questions that seem “big” :
// Write out the output order
async function async1() {
console.log('async1');
}
async function async2() {
console.log('async2 start');
await async1();
console.log('async2 end');
}
console.log('start');
setTimeout(function() {
console.log('setTimeout');
}, 0);
async2();
new Promise(function(resolve) {
console.log('promise1');
resolve();
}).then(function() {
console.log('promise2');
});
console.log('the end');Copy the code
In fact, based on the rules mentioned above, we can make the following generalizations:
- Determine the number of macro tasks (2)
- Determine the number and call order of microtasks (script: [‘async2 end’, ‘promise2’], setTimeout: [])
- Determine the call order of macro tasks (script -> setTimeout)
The following solutions can be obtained:
- Synchronous execution
console.log('start')
/console.log('async2 start')
/console.log('async1')
/console.log('promise1')
/The console. The log (' end ')
; - Execute the microtask queue
console.log('async2 end')
/console.log('promise2')
; - Perform setTimeout
console.log('setTimeout')
; - SetTimeout No microtasks, end.
Of course, this topic also involves the knowledge of Async/Await. I suggest you have a detailed understanding of Teacher Ruan Yifeng’s ES6 Tutorial es6.ruanyifeng.com/#docs/async
Four,
When I encountered this kind of problem at work, I found that the way I had learned before was very wild. In fact, I could not touch the knowledge here at work at all. To sum up, only by deep thinking can I understand the knowledge from the principle.
Five, the reference
- The heavy learn front-end time.geekbang.org/column/intr…
- “The Tasks, microtasks, the queues and schedules,” jakearchibald.com/2015/tasks-…
- The JavaScript running mechanism a: talk about the Event Loop “www.ruanyifeng.com/blog/2014/1…