当前位置:网站首页>Promise solves asynchrony
Promise solves asynchrony
2022-07-29 02:02:00 【Struggling young man】
A simple question , Show you Promise How to solve the asynchronous problem .
A case of reading files , The operating environment is node. The way to read the file is to use node Built-in module fs Inside readFile, This method itself is an asynchronous method , Of course, it also has synchronization methods , Here because of use Promise solve the problem , There is no need to synchronize .
Project directory
├─a.txt
├─b.txt
├─c.txt
├─fs.js
└package.json
a.txt,b.txt,c.txt The contents in are written 3 Secondary file name , such as
a.txt
aaa
stay fs.js Write and read the file code in the file
fs.readFile("./a.txt", "utf-8", (err, dataStr) => {
if (err) {
console.log(" Read failed ");
} else {
console.log(dataStr);
}
})
fs.readFile("./b.txt", "utf-8", (err, dataStr) => {
if (err) {
console.log(" Read failed ");
} else {
console.log(dataStr);
}
})
fs.readFile("./c.txt", "utf-8", (err, dataStr) => {
if (err) {
console.log(" Read failed ");
} else {
console.log(dataStr);
}
})
This is the code we usually write , The order of output results depends entirely on
Task queueThe mood of the . I want my code to be my own ,Output order :aaa->bbb->ccc
Use callback function nesting callback function writing
fs.readFile("./a.txt", "utf-8", (err, dataStr) => {
if (err) {
return console.log(err.message);
}
console.log(dataStr);
fs.readFile("./b.txt", "utf-8", (err, dataStr) => {
if (err) {
return console.log(err.message);
}
console.log(dataStr);
fs.readFile("./c.txt", "utf-8", (err, dataStr) => {
if (err) {
return console.log(err.message);
}
console.log(dataStr);
})
})
})
This output is OK , The order is aaa->bbb->ccc.
Have you found that the code is not easy to read ? Or the code is not beautiful ? It's not easy to maintain ?
This is the typical
Back to hellExample , The code is not beautiful , It's not easy to read . It is also the programming method that our front-end developers try to avoid
Use Promise solve the problem
//promise
var p = function (url) {
return new Promise((reslove, reject) => {
fs.readFile(url, "utf-8", (err, dataStr) => {
if (err) {
reject(err.message)
}
reslove(dataStr)
})
})
}
p("./a.txt")
.then((data) => {
console.log(data);
return p("./b.txt")
})
.then((data) => {
console.log(data);
return p("./c.txt")
})
.then((data) => {
console.log(data);
})
.catch((msg) => {
console.log(msg);
})
Does this look much more comfortable ?Promise Its function is to transform the bad programming method of asynchronism into synchronous programming , Both elegant , And beautiful .
边栏推荐
- 数学建模——永冻土层上关于路基热传导问题
- [the road of Exile - Chapter 8]
- The basic concept of transaction and the implementation principle of MySQL transaction
- LM13丨形态量化-动量周期分析
- In depth analysis of C language memory alignment
- How to protect WordPress website from network attack? It is essential to take safety measures
- 给LaTeX公式添加优美的注解;日更『数据科学』面试题集锦;大学生『计算机』自学指南;个人防火墙;前沿资料/论文 | ShowMeAI资讯日报
- About df['a column name'] [serial number]
- 知道创宇上榜CCSIP 2022全景图多个领域
- Leetcode 113: path sum II
猜你喜欢

数据平台数据接入实践
![[the road of Exile - Chapter 2]](/img/98/0a0558dc385141dbb4f97bc0e68b70.png)
[the road of Exile - Chapter 2]

Introduction to shared data center agent

The brutal rule of blackmail software continues, and attacks increase by 105%

Process -- user address space and kernel address space

【GoLang】网络连接 net.Dial
![[网鼎杯 2020 朱雀组]Nmap](/img/22/1fdf716a216ae26b9110b2e5f211f6.png)
[网鼎杯 2020 朱雀组]Nmap

Have you ever encountered the situation that the IP is blocked when crawling web pages?
![[WesternCTF2018]shrine](/img/c1/c099f8930902197590052630281258.png)
[WesternCTF2018]shrine

Add graceful annotations to latex formula; "Data science" interview questions collection of RI Gai; College Students' computer self-study guide; Personal firewall; Cutting edge materials / papers | sh
随机推荐
Tda75610-i2c-determination of I2C address of analog power amplifier
Top network security prediction: nearly one-third of countries will regulate blackmail software response within three years
【Golang】- runtime.Goexit()
Comprehensive explanation of "search engine crawl"
[7.21-26] code source - [good sequence] [social circle] [namonamo]
TDA75610-I2C-模拟功放I2C地址的确定
Come on, handwritten RPC S2 serialization exploration
Where will Jinan win in hosting the first computing power conference?
[golang] synchronization lock mutex
Use POI to export excel file, image URL to export file, image and excel file to export compressed package
As long as I run fast enough, it won't catch me. How does a high school student achieve a 70% salary increase under the epidemic?
剑指offer专项突击版第13天
【golang】使用select {}
[7.27] code source - [deletion], [bracket sequence], [number replacement], [game], [painting]
科研环境对人的影响是很大的
[understanding of opportunity-54]: plain book-1-the origin of things [original chapter 1]: the road is simple.
[web technology] 1395 esbuild bundler HMR
Planning mathematics final exam simulation II
Anaconda environment installation problem
Random talk on distributed development