Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of Node.js using examples

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "Node.js use example Analysis". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Non-blocking Istroke O of Node.js

Input/Output O is the input and output of a system.

The difference between blocking and non-blocking Icano is whether the system can receive other inputs during the period from the input to the output.

Take ordering food as an example: when you go to the canteen to order food, you have to wait in line. In this process, the aunt can only receive one person at a time. In the process of "ordering-the aunt shakes the spoon to load the food-give the food to you", the aunt can not accept other people's orders. This is blocking Ihand O. When you go to a restaurant to order, you can ask the waiter to have scrambled eggs with tomatoes. The waiter wrote it down and gave it to the back chef. At this time, when another table came, the waiter beckoned the waiter to say that he wanted to eat crayfish. That is to say, the waiter received other people's orders before serving the food to you, and this is the non-blocking Icord O.

The main point of understanding non-blocking IBO is that

Identify a system for Input/Output.

Think about whether other Icano can be carried out in the process of Icano.

Well, in the case of ordering and eating, a system for Input/Output is ordering-post-kitchen (aunt) processing-serving is a system that allows you to eat; ordering is Input, and serving is Output. In this case, the key to judging whether the two are non-blocking or blocking is whether you can accept other orders during the ordering process. For example, if you order a Buddha jumping over the wall, it may take a long time to wait for the food, and then the people who come will order some simple dishes, stir-frying a portion of fried powder a minute, which may be that they haven't been able to serve you after several waves of people going back and forth.

While Node.js is used to manipulate the computer, some operations, such as reading files, are very time-consuming, if you can not carry out other I and O, then the processing efficiency will be very low, which is also one of the reasons why Node.js is a non-blocking I-O.

Event Loop of Node.js

When Node.js starts, it initializes the event loop provided by libuv. Each event loop consists of six phases, which are executed repeatedly in the following order in each event loop, as shown below:

Timers phase: this phase executes the callback of timer (setTimeout, setInterval)

Callbacks O phase: handles a few unexecuted callbacks from the previous loop

Idle,prepare phase: for internal use only in Node

Poll phase: get a new Ithumb O event, where Node will block under appropriate conditions

Check phase: execute the callback of setImmediate ()

Close callbacks phase: execute close event callback of socket

Each stage has a first-in, first-out (FIFO) queue for callbacks. When the event loop runs to each stage, the callback function is taken from the corresponding callback queue to execute until the queue is exhausted or the maximum number of callbacks is executed.

The event loop then moves on to the next stage, and then takes the callback function from the queue corresponding to the next phase for execution, repeating until the last stage of the event loop. The event loop is also executed one by one until the end of the process.

The relationship between the six macro queues and the micro-queues in the event loop is as follows: the micro-queue (microtask) executes between the stages of the event cycle, or between the corresponding macro queues (macrotask) of each stage of the event loop.

Here is a particularly confusing version change:

If it is Node10 and its previous version: there are several macro tasks in the macro queue, the micro tasks in the micro queue will not be executed until all the macro tasks in the macro queue have been executed.

For Node11 and later versions: as soon as you execute one of the macro tasks in the corresponding macro queue in a phase (one of setTimeout,setInterval and setImmediate, excluding IMacro O), you will immediately execute the micro task queue, and then go back to the previous macro queue to execute the next macro task. This is consistent with running on the browser side.

Node.js Asynchronous programming-callback

Format specification of callback function

Error-first callback

Node-style callback

The first parameter is error, and the next parameter is the result.

/ / the first parameter is error capture interview (function (err, res) {if (err) {console.log ('cry') return;} console.log (' smile')}) function interview (callback) {setTimeout () = > {if (Math.random () > 0.2) {callback (null, 'success')} else {callback (new Error (' fail'))}}, 500)}

Asynchronous process control: callback dungeon, asynchronous concurrency and other problems

Npm:async.js; can control asynchronous flow through async.js.

Thunk: a programming method

Node.js Asynchronous programming-Promise

It can be taken literally that Promise means commitment; there are no results in the current event cycle, but future event cycles will give you results.

It is a state machine, and once the state is determined to be resolved or rejected, it will not change.

Pending: the initial state, the state in which the result has not yet been obtained

Fulfilled / resolved: success status

Rejected: failure statu

Chain calls:. Then and. Catch

The Promise of resolved status will call back the first. Then

The Promise of the rejected state calls back the first. Catch that follows.

Any Promise with a rejected state and no .catch after it will cause a global error in the browser / Node environment

/ / State transition of promise and getting content through then const promise = new Promise ((resolve, reject) = > {setTimeout (function () {resolve (3); / / reject (new Error (4))}, 500)}) promise.then (function (result) {console.log (result)}) .catch (function (err) {console.log (err)}) setTimeout (() = > {console.log (promise)}, 800)

Executing then and catch returns a new Promise, and the final state of the Promise is determined by the execution result of the callback functions of then and catch

If the callback function ends up being throw, the Promise is the rejected state

If the callback function ends up being return, the Promise is the resolved state

But if the callback function ends up return a Promise, the Promise will be consistent with the Promise state of the callback function return

Node.js Asynchronous programming-async/await

Async function is the grammatical sugar encapsulation of Promise

The Ultimate solution of Asynchronous programming-write Asynchronous in a synchronous way

The await keyword can "pause" the execution of async function

The await keyword can be written synchronously to obtain the execution result of Promise.

Try-catch can get the error obtained by await

(async function () {await findJob () console.log ('trip')}) () async function findJob () {try {/ / conduct three rounds of interviews await interview (1); await interview (2); await interview (3) Console.log ('smile')} catch (e) {console.log (' cry at'+ e.round)} / / Round interview function interview (round) {return new Promise ((resolve, reject) = > {setTimeout () = > {if (Math.random () < 0.2) {const error = new Error ('failed'); error.round = round; reject (error) } else {resolve ('success');}}, 500)})

This is a function that exists through the event loop.

This is the end of "Node.js usage sample Analysis". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report