Deeply understand the meaning of NodeJs asynchronous programming
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

How does Node.js do GC (garbage collection)? The following article will take you through it.

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package
