Table of Contents
First understand what asynchronous programming is
2. Why is there asynchronous programming?
3. How to deal with problems that arise in asynchronous programming
Home Web Front-end JS Tutorial Deeply understand the meaning of NodeJs asynchronous programming

Deeply understand the meaning of NodeJs asynchronous programming

Aug 08, 2022 pm 02:38 PM
node.js

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');
Copy after login

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(&#39;end&#39;);
Copy after login

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(&#39;fs&#39;)
const path =require(&#39;path&#39;)
let p1=path.join(&#39;1.txt&#39;)
let p2=path.join(&#39;2.txt&#39;)
let p3=path.join(&#39;3.txt&#39;)
fs.readFile(p1,&#39;utf8&#39;,(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)
        })
    })
})
Copy after login

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
})
Copy after login

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()
Copy after login

[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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

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!

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

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

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

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.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

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!

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

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.

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

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!

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

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

Learn more about Buffers in Node Learn more about Buffers in Node Apr 25, 2023 pm 07:49 PM

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

See all articles