Home>Article>Web Front-end> Deeply understand the meaning of NodeJs asynchronous programming

Deeply understand the meaning of NodeJs asynchronous programming

藏色散人
藏色散人 forward
2022-08-08 14:38:14 1739browse

First understand what asynchronous programming is

Meaning:

  • There will definitely be synchronization if there is asynchronous

  • Any callback function that exists is asynchronous code

  • Execute the synchronous code first , after seeing the asynchronous code, put the asynchronous code into the asynchronous code execution area (not executed first)

  • Continue to execute the synchronous code. When all the synchronous codes are executed, execute the asynchronous code Code

Asynchronous code example:

console.log('1'); setTimeout(()=>{ console.log('2秒后再执行...'); },2000); console.log('end');

The output result after the program is executed:
1
Ende
2 Execute again after seconds...

Summary: The code will be executed sequentially during execution, but when the callback function is executed, the callback function will be put into the asynchronous code execution area and will not be executed first. If the code is executed After that, execute them one by one and put them into the asynchronous code execution area.

Synchronized code line case:

for(let i=0;i<10;i++){ console.log(i); } console.log('end');

The output result after the program is executed:
0123456789
end
Summary : Synchronous code, no matter how long the for loop is executed, the following code will wait for it to complete before it is executed.

2. Why is there asynchronous programming?

nodejs is characterized by single-threaded, asynchronous, and non-blocking. If the code logic involves multiple callbacks, very terrible code will appear. No Conducive to later maintenance.

The role of asynchronous programming is to improve efficiency. Nowadays, programs are getting larger and larger, and the pressure on the CPU and memory is also increasing. Asynchrony allows the computer to process multiple transactions at the same time, so asynchronous programming is needed.

3. How to deal with problems that arise in asynchronous programming

In our project, there will be some problems. For example, if the value cannot be obtained, it is undefined, because of asynchronous programming.
Solution: Callback function nesting, Promise, await, and async syntactic sugar become synchronization

Now there are three txt files 1, 2, and 3 in the folder, and we need to read these three files , if the first pass is read directly, the order may be out of order for the second pass, so we need to deal with the asynchronous problem and let it be executed in order

Use callback functions to nest the code:

const fs=require('fs') const path =require('path') let p1=path.join('1.txt') let p2=path.join('2.txt') let p3=path.join('3.txt') fs.readFile(p1,'utf8',(err,data)=>{ if(err) throw err console.log(data) fs.readFile(p2,'utf8',(err,data)=>{ if(err) throw err console.log(data) fs.readFile(p3,'utf8',(err,data)=>{ if(err) throw err console.log(data) }) }) })

Use Promise code:

// new promise 的作用:让异步代码马上执行 const fs=require('fs') function readFile(path){ return new Promise((resolve,reject)=>{ fs.readFile(path,'utf8',(err,data)=>{ resolve(data) }) }) } let p1=readFile('1.txt') let p2=readFile('2.txt') let p3=readFile('3.txt') p1.then(result=>{ console.log(result) return p2 }).then(result=>{ console.log(result) return p3 }).then(result=>{ console.log(result) return p3 })

You can also use await and async syntax sugar code:

const path=require('path') const fs=require('fs') let p1=readFile('1.txt') let p2=readFile('2.txt') let p3=readFile('3.txt') var readfile=(path)=>{ return new Promise((resolve,reject)=>{ fs.readFile(path,'utf8',(err,data)=>{ resolve(data) }) }) } async function exec() { await readfile(p1).then(result => console.log(result)) await readfile(p2).then(result => console.log(result)) await readfile(p3).then(result => console.log(result)) } exec()

[Recommended:node.js video tutorial]

The above is the detailed content of Deeply understand the meaning of NodeJs asynchronous programming. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete