You get to know the band with a giant face questions event loop mechanism

This article covers

  • The introduction of face questions
  • Some question the order of execution of the event loop face questions
  • By face questions on the micro-task, the event loop, timers and other in-depth understanding of
  • Conclusion summary

Interview questions

Face questions below, you can first try to write about the output, and then look at me explain in detail below, to see will not have any access, find out if the entire sequence Node.js implementation of the order should be no problem.

async function async1(){    console.log('async1 start')    await async2()    console.log('async1 end')  }async function async2(){    console.log('async2')}console.log('script start')setTimeout(function(){    console.log('setTimeout0') },0)  setTimeout(function(){    console.log('setTimeout3') },3)  setImmediate(() => console.log('setImmediate'));process.nextTick(() => console.log('nextTick'));async1();new Promise(function(resolve){    console.log('promise1')    resolve();    console.log('promise2')}).then(function(){    console.log('promise3')})console.log('script end')

Face questions correct output results

script startasync1 startasync2promise1promise2script endnextTickasync1 endpromise3setTimeout0setImmediatesetTimeout3

submit questions

In asynchronous node.js understanding of when some do not know where, using node.js developers must know that it is single-threaded, asynchronous and does not block high concurrent one language, but in asynchronous node.js when two asynchronous task of opening up, that is, who is quickly who should complete that simple, or that there will be a final asynchronous task execution order has? for a single-threaded asynchronous language of it is how to achieve high concurrency it ?

Well then we took these two issues to really understand the node.js asynchronous (micro tasks and event loop).

Node asynchronous syntax is more complex than the browser, because it can dialogue with the kernel had to engage in a special library libuv do it. This library is responsible for the execution of various callback time, event-based asynchronous tasks last cycle mechanism or to return to the main thread, a queued execution.

I was for many years engaged in the development of a web front-end programmers old, currently doing his resignation in customized web front-end private course, I spent a month earlier this year put together a 2019 study of the most suitable web front-end learning dry goods, various frameworks have sort, given to every small front-end partners, want to get the attention I can add my web front-end and exchange skirt: 600 610 151, you can get free.

Explain in detail

1. round loop and sub-loop round

Asynchronous tasks can be divided into two kinds.

  1. Additional asynchronous tasks in the current round of cycle
  2. Additional asynchronous tasks in the second round of the cycle

The so-called "cycle" refers to an event loop (event loop). This is the way JavaScript engine handles asynchronous tasks, explained in detail later. Once you understand this, the current round of early implementation of certain cycle to cycle in the second round.

Node provisions, process.nextTick and Promise callback function, added in the current round of cycle, that synchronous task once the implementation is completed, begin to execute them. The setTimeout, setInterval, setImmediate callback function, an additional cycle in the second round.

2.process.nextTick()

1) process.nextTick not because there is next to be treated as second-round cycle of a lot of small partners.

2) Node synchronization after executing all tasks, then it will perform process.nextTick task queue.

3) development process if you want to perform asynchronous task as quickly as possible, you can use process.nextTick to complete.

3. Micro-task (microtack)

According to the language specification, Promise callback object, will enter the asynchronous task inside the "micro-tasks" (microtask) queue.

Additional micro-task queue behind the queue process.nextTick, also belong to cycle round.

According to the language specification, Promise callback object, will enter the asynchronous task inside the "micro-tasks" (microtask) queue.

Additional micro-task queue behind the queue process.nextTick, also belong to cycle round. Therefore, the following code is always output first 3, 4 and then output.

process.nextTick(() => console.log(3));Promise.resolve().then(() => console.log(4));

// output 3,4

process.nextTick(() => console.log(1));Promise.resolve().then(() => console.log(2));process.nextTick(() => console.log(3));Promise.resolve().then(() => console.log(4));

// output 1,3,2,4

Note that only after a queue before all the empty, will perform the next queue. The concept nextTickQueue two queues and microqueue microTaskQueue, that is also divided into several open asynchronous tasks, such as Promise objects, then turned directly into the micro queue, is that tasks within microqueue quickly finished the first execution but for the queue and queue between different tasks, or have the order, the order is determined by the queue.

4. The event loop of stages (idle, prepare ignore this stage)

The most detailed explanation of events circulating most stages (official website: https: //nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout)

  1. second phase includes timers stage setTimeout () and setInterval ()
  2. IO callbacks most callbacks, ordinary caollback
  3. poll stage network connection, data acquisition, and other operations to read the file
  4. check stage setImmediate () callback is invoked here
  5. Some close off the callback phase, e.g. socket.on ( 'close', ...)
  • Precautions event loop

1) Node start script is executed, it will be initialized event loop, but this time the event loop has not yet begun, will be completed the following things.

Time synchronization task asynchronous request issued Timer planning entry into force of execution process.nextTick (), etc.

Finally, on top of these things are finished, the event loop officially began.

2) After the event loop run in the same single-threaded environment, but also rely on complicated high cycle events, each event is generated, the corresponding phase will be added to the queue, the event loop was taken out at this time in the event queue, ready to execute the Callback.

3) assuming that the event loop now entered a stage, even if there are other events in the queue ready, also finished first all callback methods during this period after the current queue, and then move to the next stage.

The event loop setTimeOut and setImmediate

Since setTimeout executed timers stage and perform in check setImmediate stage. So, setTimeout will be completed earlier than setImmediate.

setTimeout(() => console.log(1));setImmediate(() => console.log(2));

The above code should first output 1, 2 and then output, but the actual execution, the result is uncertain, and sometimes the first output 2, then output 1.

This is because the second argument setTimeout defaults to 0. But in fact, the Node 0 ms do, also require a minimum of 1 millisecond, according to an official document, the second parameter is in the range between 1 ms and 2147483647 ms. That is, setTimeout (f, 0) is equivalent to setTimeout (f, 1).

When the actual execution, after entering the event loop, it is possible to 1 millisecond to millisecond may not, depending on the status of the system at the time. If not to the 1 millisecond, then the stage will skip timers, enter the check stage, perform setImmediate callback function.

However, the following code 2 must be output first, and then an output.

const fs = require('fs');fs.readFile('test.js', () => { setTimeout(() => console.log(1)); setImmediate(() => console.log(2));});

The above code will first enter the I / O callbacks stage, then check phase, and finally timers stage. Therefore, setImmediate will be executed as early as in setTimeout.

6. Synchronize tasks and promise of some misconceptions async

  • Question 1:

In the face questions, during synchronization task, I do not know if you have questions, why not finished after the execution async2 output execution async1 end output, but then perform promise1?

Quoted in the book saying: "async function returns a Promise object when the function is executed, the event will first await the return until the asynchronous operation triggered completed, followed by the implementation of the back of the body of the function statement."

Simply put, go back to perform synchronization task code, execution is completed, that is the expression of Promise parsed continue async function and returns the results to solve. (In fact, the current round of circulatory problems or promise, the final part of asynchronous resolve, at the end of the current round of the loop.)

  • Question 2:

console.log ( 'promise2') Why is executed before the resolve?

ANSWER: Note: This content source and Ruan Yifeng teacher ES6 books, call reject and will not resolve or terminate the enforcement of the promise of function parameters. Because of Promise is resolved immediately executed at the end of the current round of cycle, while always later than the sync task round cycle. Formal written call resolve or reject later, Promise mission is complete, then subsequent operations should be placed behind the method. So it is best in front of it plus the return statement, so there are no surprises

new Promise((resolve,reject) => {    return resolve(1);    //后面的语句不会执行    console.log(2);}
  • Question 3:

Promise3 order of execution and script end whether there is doubt?

Answer: Because immediately resolved Promise is executed at the end of the current round of cycle, but always later than the current round of cycle synchronization tasks. Promise is a function executed immediately, but his success (or failure: reject) resolve callback function is executed an asynchronous callback. When executing to resolve (), this task will be put to the callback queue, waiting for the call stack free time cycling event again removed it. Round the loop last executed.

Overall conclusion

You get to know the band with a giant face questions event loop mechanism

 

Overall conclusion is that the order of: synchronization tasks -> round loop -> second-round cycle

Guess you like

Origin www.cnblogs.com/Vay123/p/12108188.html