当前位置:网站首页>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的作用就是把异步这种不好的编程方式转变成同步编程,既优雅,又美观。
边栏推荐
- DSP vibration seat
- [WesternCTF2018]shrine
- 【流放之路-第五章】
- Comprehensive analysis of news capture doorway
- [web technology] 1395 esbuild bundler HMR
- Secret skill winter tide branding skill matching
- Lua log implementation -- print table
- Top network security prediction: nearly one-third of countries will regulate blackmail software response within three years
- [netding cup 2020 rosefinch group]nmap
- 【Web技术】1395- Esbuild Bundler HMR
猜你喜欢

For a safer experience, Microsoft announced the first PC with a secure Pluto chip

Stonedb invites you to participate in the open source community monthly meeting!

Day01作业

【观察】三年跃居纯公有云SaaS第一,用友YonSuite的“飞轮效应”

给LaTeX公式添加优美的注解;日更『数据科学』面试题集锦;大学生『计算机』自学指南;个人防火墙;前沿资料/论文 | ShowMeAI资讯日报

【10点公开课】:快手GPU/FPGA/ASIC异构平台的应用探索

Super scientific and technological data leakage prevention system, control illegal Internet behaviors, and ensure enterprise information security

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

Why does stonedb dare to call it the only open source MySQL native HTAP database in the industry?

Making high-precision map based on autoware (V)
随机推荐
覆盖接入2w+交通监测设备,EMQ为深圳市打造交通全要素数字化新引擎
知道创宇上榜CCSIP 2022全景图多个领域
[WesternCTF2018]shrine
为什么 BI 软件都搞不定关联分析
【GoLang】网络连接 net.Dial
Some summaries of ibatis script and provider
[netding cup 2020 rosefinch group]nmap
[7.21-26] code source - [square count] [dictionary order minimum] [Z-type matrix]
More interesting Title Dynamic Effect
使用POI,实现excel文件导出,图片url导出文件,图片和excel文件导出压缩包
Making high-precision map based on autoware (V)
【7.21-26】代码源 - 【好序列】【社交圈】【namonamo】
Explanation of yocto project directory structure
[the road of Exile - Chapter 4]
Minimalist thrift+consumer
Tomorrow infinite plan, 2022 conceptual planning scheme for a company's yuanuniverse product launch
TDA75610-I2C-模拟功放I2C地址的确定
Network security litigation risk: four issues that chief information security officers are most concerned about
LeetCode 113:路径总和 II
How companies make business decisions -- with the help of data-driven marketing