当前位置:网站首页>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 .
边栏推荐
猜你喜欢

Day01 job

【流放之路-第二章】

Make logic an optimization example in sigma DSP - data distributor

How companies make business decisions -- with the help of data-driven marketing
![[golang] use select {}](/img/30/fa593ec682a40c47689c1fd88f9b83.png)
[golang] use select {}

DSP vibration seat

druid. The performance of IO + tranquility real-time tasks is summarized with the help of 2020 double 11

知道创宇上榜CCSIP 2022全景图多个领域
![Golang run times undefined error [resolved]](/img/9b/3379aeeff59b47531fe277f7422ce7.png)
Golang run times undefined error [resolved]

Planning mathematics final exam simulation II
随机推荐
The basic concept of transaction and the implementation principle of MySQL transaction
What is a proxy server? [2022 guide]
[web technology] 1395 esbuild bundler HMR
In depth analysis of C language memory alignment
Network security litigation risk: four issues that chief information security officers are most concerned about
Super scientific and technological data leakage prevention system, control illegal Internet behaviors, and ensure enterprise information security
MPEG音频编码三十年
Comprehensive explanation of "search engine crawl"
【MySQL】sql给表起别名
Minimalist thrift+consumer
Code reading - ten C open source projects
把逻辑做在Sigma-DSP中的优化实例-数据分配器
[7.27] code source - [deletion], [bracket sequence], [number replacement], [game], [painting]
How companies make business decisions -- with the help of data-driven marketing
Practical experience of Google cloud spanner
ciscn 2022 华中赛区 misc
Use of packet capturing tool Charles
数学建模——自来水管道铺设问题
[the road of Exile - Chapter 7]
数学建模——红酒品质分类