当前位置:网站首页>Promise解决异步
Promise解决异步
2022-07-29 01:13:00 【抗争的小青年】
一个简单问题,带你体会Promise是如何解决异步问题。
一个读取文件的案例,运行环境是node。读取文件的方法是用node内置模块fs里的readFile,这个方法本身就是一个异步方法,当然它也有同步方法,这里因为用Promise解决问题,就不用同步方法了。
项目目录
├─a.txt
├─b.txt
├─c.txt
├─fs.js
└package.json
a.txt,b.txt,c.txt里的内容均是书写3次文件名,比如
a.txt
aaa
在fs.js文件中书写读取文件代码
fs.readFile("./a.txt", "utf-8", (err, dataStr) => {
if (err) {
console.log("读取失败");
} else {
console.log(dataStr);
}
})
fs.readFile("./b.txt", "utf-8", (err, dataStr) => {
if (err) {
console.log("读取失败");
} else {
console.log(dataStr);
}
})
fs.readFile("./c.txt", "utf-8", (err, dataStr) => {
if (err) {
console.log("读取失败");
} else {
console.log(dataStr);
}
})
这种就是咱们平常写出来的代码,输出结果的顺序完全看
任务队列的心情。我想要我的代码我做主,输出顺序:aaa->bbb->ccc
使用回调函数嵌套回调函数写法
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);
})
})
})
这种输出没问题了,顺序就是aaa->bbb->ccc.
大家有没有发现代码不太好读了?或者说代码不美观了?不好维护了?
这种就是典型的
回调地狱的例子,代码不美观,不好读。也是我们前端开发人员尽力避免的编程方式
使用Promise解决问题
//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);
})
这样是不是看起来舒服多了?Promise的作用就是把异步这种不好的编程方式转变成同步编程,既优雅,又美观。
边栏推荐
- ciscn 2022 华中赛区 misc
- Network security litigation risk: four issues that chief information security officers are most concerned about
- Data security is a competitive advantage. How can companies give priority to information security and compliance
- What are the common cyber threats faced by manufacturers and how do they protect themselves
- The information security and Standardization Commission issued the draft for comments on the management guide for app personal information processing activities
- 把逻辑做在Sigma-DSP中的优化实例-数据分配器
- MySQL execution order
- 【10点公开课】:快手GPU/FPGA/ASIC异构平台的应用探索
- Reinforcement learning (II): SARS, with code rewriting
- [7.21-26] code source - [good sequence] [social circle] [namonamo]
猜你喜欢

Six simple techniques to improve the value of penetration testing and save tens of thousands of yuan

StoneDB 邀请您参与开源社区月会!

How to crawl web pages with playwright?

Leetcode 113: path sum II

Tda75610-i2c-determination of I2C address of analog power amplifier
![[WesternCTF2018]shrine](/img/c1/c099f8930902197590052630281258.png)
[WesternCTF2018]shrine

DSP vibration seat

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

What is the ISO assessment? How to do the waiting insurance scheme
随机推荐
[WesternCTF2018]shrine
The information security and Standardization Commission issued the draft for comments on the management guide for app personal information processing activities
【观察】三年跃居纯公有云SaaS第一,用友YonSuite的“飞轮效应”
Where will Jinan win in hosting the first computing power conference?
[understanding of opportunity-54]: plain book-1-the origin of things [original chapter 1]: the road is simple.
Random talk on distributed development
Reinforcement learning (III): dqn, nature dqn, double dqn, with source code interpretation
分布式开发漫谈
Reinforcement learning (II): SARS, with code rewriting
[the road of Exile - Chapter 6]
【Golang】- runtime.Goexit()
ELS new box falls
Secret skill winter tide branding skill matching
【流放之路-第三章】
MySQL execution order
MPEG音频编码三十年
为什么 BI 软件都搞不定关联分析
[the road of Exile - Chapter 4]
科研环境对人的影响是很大的
[网鼎杯 2020 朱雀组]Nmap