当前位置:网站首页>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的作用就是把异步这种不好的编程方式转变成同步编程,既优雅,又美观。
边栏推荐
- 九天后我们一起,聚焦音视频、探秘技术新发展
- Dynamic memory and smart pointer
- [public class preview]: application exploration of Kwai gpu/fpga/asic heterogeneous platform
- Leetcode 113: path sum II
- 科研环境对人的影响是很大的
- 【流放之路-第八章】
- 5G 商用第三年:无人驾驶的“上山”与“下海”
- 【观察】三年跃居纯公有云SaaS第一,用友YonSuite的“飞轮效应”
- Large scale web crawling of e-commerce websites (Ultimate Guide)
- Talk about possible problems when using transactions (@transactional)
猜你喜欢
Large scale web crawling of e-commerce websites (Ultimate Guide)
[observation] ranked first in SaaS of pure public cloud in three years, and yonsuite's "flywheel effect"
给LaTeX公式添加优美的注解;日更『数据科学』面试题集锦;大学生『计算机』自学指南;个人防火墙;前沿资料/论文 | ShowMeAI资讯日报
[WesternCTF2018]shrine
规划数学期末模拟考试一
[the road of Exile - Chapter 7]
【流放之路-第二章】
With the explosive growth of digital identity in 2022, global organizations are facing greater network security
移动通信——基于卷积码的差错控制系统仿真模型
数学建模——红酒品质分类
随机推荐
MySQL execution order
The basic concept of transaction and the implementation principle of MySQL transaction
Super technology network security risk assessment service, comprehensively understand the security risks faced by the network system
Wonderful use of data analysis
Comprehensive explanation of "search engine crawl"
Tomorrow infinite plan, 2022 conceptual planning scheme for a company's yuanuniverse product launch
Large scale web crawling of e-commerce websites (Ultimate Guide)
[the road of Exile - Chapter 6]
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
数学建模——带相变材料的低温防护服御寒仿真模拟
Why does stonedb dare to call it the only open source MySQL native HTAP database in the industry?
数学建模——自来水管道铺设问题
【流放之路-第五章】
Slow storage scheme
【流放之路-第七章】
剑指offer专项突击版第13天
【流放之路-第八章】
Data platform data access practice
StoneDB 邀请您参与开源社区月会!
Nine days later, we are together to focus on the new development of audio and video and mystery technology