当前位置:网站首页>简单理解ES6的Promise
简单理解ES6的Promise
2022-07-06 09:21:00 【玲小叮当】
简单理解ES6的Promise
前言
Promise
是异步编程的一种解决方案:从语法上讲,promise
是一个对象,从它可以获取异步操作的消息;从本意上讲,它是承诺,承诺它过一段时间就会给你一个结果Promise
可以保证异步请求变得有顺序执行概念:
Promise
是ES6
中的新语法,本身是一个构造函数;每个new
出来的Promise
实例对象,都代表一个异步操作作用: 解决了回调地狱问题(即异步嵌套调用问题)
回调地狱:指的是回调函数中,嵌套回调函数的代码形式;如果嵌套的层级很深,就是回调地狱;
回调地狱不利于代码的阅读、维护和后期的扩展
Promise怎么用
- 创建具体的异步操作对象
const p = new Promise(function(successCb, errorCb){
// 在这个 function 中定义具体的异步操作
// successCb成功回调
// errorCb失败回调
})
Promise
是构造函数,可以new
一个对象,本身就是一个异步操作Promise
的then
方法Promise
使用时有两个方法参数successCb
,errorCb
分别代表执行成功或失败Promise
对象可以通过then
方法对successCb
和errorCb
进行调用
具体有两种情形如下:
result.then(function(data){
/*成功回调*/},function(data){
/*失败回调*/})
result.then(function(){
/*成功回调*/}).catch(function(data){
/*失败回调*/})
前者在then
方法中通过两个参数分别接受successCb
和errorCb
回调函数
后者通过then
和catch
两个方法依次接受successCb
和errorCb
回调函数
- 例:
// 引入fs模块
const fs = require('fs')
// 4) Promise介入并丰富操作(加入成功 、失败回调)
function getFileCont(filename) {
// 实例化Promise对象,用以表示是异步操作
// new Promise(function(successCb函数, errorCb函数){})
// successCb:当前异步操作是ok情况下就触发执行resolve
// errorCb:当前异步操作发生错误情况(出乎意料)下就触发执行reject
return new Promise(function(successCb, errorCb) {
// 体现异步过程
fs.readFile(filename, 'utf8', function(err, data) {
if (err) {
return errorCb('文件读取发生错误了:' + err)
}
// 所有操作都ok情况下的正常处理,把处理后的结果给予resolve调用(返回)
successCb(data)
})
})
}
// 以下可以保证 按照顺序 获得结果
getFileCont('./files/1.txt').then(function(result) {
console.log(result)
return getFileCont('./files/2.txt')
}).then(function(result){
console.log(result)
return getFileCont('./files/3.txt')
}).then(function(result){
console.log(result)
}).catch(function(err){
console.log(err)
})
ES7的async和await
ES7
中的async
和await
可以简化Promise
调用,提高Promise
代码的阅读性和理解性async
和await
结合起来,可以使得异步调用不返回Promise
,而直接把then
参数方法的参数(也是successCb
函数实参)给返回出来,使得代码更节俭,提高代码开发效率,也可以保证异步调用的顺序执行async
、await
各种使用情形:
注意:
async
和await
必须同时出现
一个async
可以对应多个await
await
修饰的结果必须是Promise
对象
var obj = {
async getInfo(){
await getXXXX()
await getXXXX()
}
}
或
function ffff(){
// async需要设置到Promise对象的最近外层function的前边
getInfo(async function(){
await getXXXX()
//console.log(getXXXX())
})
}
或
async function XXXX(){
await getXXXX()
}
总结
new Promise()
实例化对象,参数回调函数会存在两个回调successCb
和errorCb
参数- 这两个回调可以通过
then
和catch()
进行接收,但是异步调用代码多少还有地狱回调的程度体现 async
和await
结合,把返回的Promise
直接转变为successCb
的实参,大大简化了代码开发复杂度,提升开发效率- 如果有需要,通过
try/catch
捕捉async
和await
- 通常使用,
async
、await
、异常
三种技术结合提供的异步顺序执行的解决方案
async function getThreeFile(){
try{
console.log(await getFileCont('./files/1.txt'))
console.log(await getFileCont('./files/2.txt'))
console.log(await getFileCont('./files/3.txt'))
}catch(err){
console.log(err)
}
}
getThreeFile()
边栏推荐
- 8. C language - bit operator and displacement operator
- 5. Download and use of MSDN
- Miscellaneous talk on May 14
- 5.MSDN的下载和使用
- View UI plus released version 1.3.1 to enhance the experience of typescript
- Miscellaneous talk on May 27
- 2. C language matrix multiplication
- [the Nine Yang Manual] 2018 Fudan University Applied Statistics real problem + analysis
- CorelDRAW plug-in -- GMS plug-in development -- Introduction to VBA -- GMS plug-in installation -- Security -- macro Manager -- CDR plug-in (I)
- [the Nine Yang Manual] 2021 Fudan University Applied Statistics real problem + analysis
猜你喜欢
[during the interview] - how can I explain the mechanism of TCP to achieve reliable transmission
3.猜数字游戏
5. Download and use of MSDN
PriorityQueue (large root heap / small root heap /topk problem)
The latest tank battle 2022 full development notes-1
arduino+水位传感器+led显示+蜂鸣器报警
1. C language matrix addition and subtraction method
The overseas sales of Xiaomi mobile phones are nearly 140million, which may explain why Xiaomi ov doesn't need Hongmeng
使用Spacedesk实现局域网内任意设备作为电脑拓展屏
8. C language - bit operator and displacement operator
随机推荐
PriorityQueue (large root heap / small root heap /topk problem)
一段用蜂鸣器编的音乐(成都)
Share a website to improve your Aesthetics
[the Nine Yang Manual] 2021 Fudan University Applied Statistics real problem + analysis
学编程的八大电脑操作,总有一款你不会
8. C language - bit operator and displacement operator
2022泰迪杯数据挖掘挑战赛C题思路及赛后总结
Set container
甲、乙机之间采用方式 1 双向串行通信,具体要求如下: (1)甲机的 k1 按键可通过串行口控制乙机的 LEDI 点亮、LED2 灭,甲机的 k2 按键控制 乙机的 LED1
[中国近代史] 第九章测验
8.C语言——位操作符与位移操作符
3.C语言用代数余子式计算行列式
【九阳神功】2017复旦大学应用统计真题+解析
MPLS experiment
Thoroughly understand LRU algorithm - explain 146 questions in detail and eliminate LRU cache in redis
5. Function recursion exercise
View UI plus released version 1.3.1 to enhance the experience of typescript
Change vs theme and set background picture
抽象类和接口的区别
The overseas sales of Xiaomi mobile phones are nearly 140million, which may explain why Xiaomi ov doesn't need Hongmeng