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<p>The output result after the program is executed: <br> 0123456789<br> end<br><strong>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. </strong></p><h2 id="Why-is-there-asynchronous-programming">2. Why is there asynchronous programming? </h2><p>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. </p><p>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. </p><h2 id="How-to-deal-with-problems-that-arise-in-asynchronous-programming">3. How to deal with problems that arise in asynchronous programming</h2><p>In our project, there will be some problems. For example, if the value cannot be obtained, it is undefined, because of asynchronous programming. <br> Solution: Callback function nesting, Promise, await, and async syntactic sugar become synchronization </p><p> 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 </p><p>Use callback functions to nest the code: </p><pre class="brush:php;toolbar:false">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!

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

如何用pkg打包nodejs可执行文件?下面本篇文章给大家介绍一下使用pkg将Node.js项目打包为可执行文件的方法,希望对大家有所帮助!

本篇文章带大家详解package.json和package-lock.json文件,希望对大家有所帮助!

本篇文章给大家分享一个Nodejs web框架:Fastify,简单介绍一下Fastify支持的特性、Fastify支持的插件以及Fastify的使用方法,希望对大家有所帮助!

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

本篇文章给大家分享一个Node实战,介绍一下使用Node.js和adb怎么开发一个手机备份小工具,希望对大家有所帮助!

先介绍node.js的安装,再介绍使用node.js构建一个简单的web服务器,最后通过一个简单的示例,演示网页与服务器之间的数据交互的实现。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

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

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