Home >Web Front-end >JS Tutorial >An in-depth analysis of asynchrony in Node.js
This article will give you a detailed introduction to asynchronous in Node.js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
About Node.js Asynchrony, two points cannot be avoided: Non-blocking I/O and Event loop . It is precisely because of these two points that Node.js can be called high-performance and be used in online environments. So let’s learn about the asynchronous mechanism and usage of Node.js! [Recommended learning: "nodejs Tutorial"]
/
Output, the
input and output of a system.
accepted the other dishes before serving them to you. Human order, then this is non-blocking I/O. The key to understanding non-blocking I/O is to
Determine a system for
.
Think about whether other I/OOutput is ordering - processing by the kitchen (aunt) - serving Such a system that allows you to eat; ordering food is
Input, and serving food is
Output. In this example, the key to judging whether the two are non-blocking or blocking is During the process of ordering and serving, can I accept other orders and be served? It's like if you order a Buddha Jumps Over the Wall, it may take a long time to wait for the food to be served. Then the people who come will order some simple dishes, the kind of stir-fried noodles that can be fried in one minute. Maybe after a few waves of people come and go, I haven't been able to serve you food yet.
Node.js is used to control the computer. Some operations such as reading files are very time-consuming. If other I/O cannot be performed, the processing efficiency will be very low. Yes, this is one reason why Node.js is non-blocking I/O.
Event loop of Node.js
timers
(
setTimeout,
setInterval)
I/O
callbacks
idle Phase: Only used internally by Node
poll
check's callback
close callbacks's
close event callback
Then the event loop will enter the next stage, and then the callback function will be taken out from the queue corresponding to the next stage and executed, and this will be repeated until the last stage of the event loop. The event loop will also be executed one by one until the process ends.
The relationship between the six macro queues and micro queues in the event loop is as follows: Micro queue (microtask
) is executed between various stages of the event loop, or in each stage of the event loop Executed between corresponding macro queues (macrotask).
Here is a particularly confusing version change:
setTimeout
, setInterval
and setImmediate
among the three (excluding I/O), execute the microtask queue immediately, execute all the microtasks in the microqueue, and then return to the macroqueue to execute the next macrotask. This is consistent with the browser-side operation. callback
error-first callback
node-style callback
, followed by Parameters are the result.
// 第一个参数是错误捕获 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 hell, asynchronous concurrency and other issues
:
async.js; can be passed
async.js To control asynchronous processes
: A programming method
means promise; the current event loop cannot get the result, but the future event loop It will give you the result
or
rejected it will not change
: Initial state, the state that has not yet obtained the result
/
resolved: Successful state
: Failure status
.then and
.catch
The
Promise of the state will call back the first
.then
of the state
Promise Will call back the first
.catch
status and no
Promise## followed by .catch
#, will cause a global error in the browser/Node environment
// promise的状态转换以及通过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)
and catch
will return a new Promise
, The Promise
final state is determined based on the execution results of the then
and catch
callback functions
Promise
is rejected
status
If the callback function eventually is Promise
is resolved
Status
But if the callback function finally Promise
, the Promise
will be the same as the callback functionreturn
’s Promise
state remains consistent
await
Promise
The ultimate solution for asynchronous programming – writing asynchronously in a synchronous mannerasync function
try-catch
(async function () { await findJob() console.log('trip') })() async function findJob() { try { // 进行三轮面试 await interview(1); await interview(2); await interview(3); console.log('smile') } catch (e) { console.log('cry at ' + e.round) } } // 进行第round轮面试 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) }) }
Summary
Promise, the initial state is
pending, once the state is determined to be resolved or
rejected will not change, and chain calls can be made through
.then and
.catch.
async
Writing asynchronous in a synchronous way is the ultimate solution to asynchronous programming.
For more programming related knowledge, please visit: The above is the detailed content of An in-depth analysis of asynchrony in Node.js. For more information, please follow other related articles on the PHP Chinese website!