当前位置:网站首页>Promise learning (2) An article takes you to quickly understand the common APIs in Promise
Promise learning (2) An article takes you to quickly understand the common APIs in Promise
2022-08-01 10:33:00 【I'm sorry the user has become immortal】
目录
- 前言
- Promise 常用的API方法
- 1. Promise 构造函数: Promise (excutor) {}
- 2. Promise.prototype.then 方法: (onResolved, onRejected) => {}
- 3. Promise.prototype.catch 方法: (onRejected) => {}
- 4. Promise.resolve 方法: (value) => {}
- 5. Promise.reject 方法: (reason) => {}
- 6. Promise.all 方法: (promises) => {}
- 7. Promise.race 方法: (promises) => {}
- 8. Promise.prototype.finally 方法
- 9. Promise.any 方法
- 10. Promise.allSettled 方法
前言
This article is through Shang Silicon Valley teacherPromise教程和阮一峰ES6教程And some other network resources for summary learning.
Promise 常用的API方法
1. Promise 构造函数: Promise (excutor) {}
(1) executor 函数: 执行器(resolve, reject) => {}
(2) resolve 函数: 内部定义成功时我们调用的函数 value => {}
(3) reject 函数: 内部定义失败时我们调用的函数 reason => {}
说明: executor 会在 Promise 内部立即
同步调用
,异步操作在执行器中执行,换话说Promise支持同步也支持异步操作
2. Promise.prototype.then 方法: (onResolved, onRejected) => {}
Promise 实例具有then
方法,也就是说,then
方法是定义在原型对象Promise.prototype
上的.它的作用是为 Promise 实例添加状态改变时的回调函数.前面说过,then方法的第一个参数是resolved
状态的回调函数,第二个参数(可选)是rejected
状态的回调函数.
- onResolved 函数: 成功的回调函数
(value) => {}
- onRejected 函数: 失败的回调函数
(reason) => {}
then
方法返回的是一个新的Promise实例- 注意,不是原来那个Promise实例,因此可以采用链式写法,即
then
方法后面再调用另一个then
方法.
const test = n => {
return new Promise((resolve, reject) => {
// 异步任务
setTimeout(() => {
resolve(n);
}, 1000);
});
}
test(1).then(value => {
console.log(value);
return test(2);
}).then(value => {
console.log(value);
return test(3);
}).then(value => {
console.log(value);
});
上面的代码使用
then
方法,Multiple callback functions are specified in turn.第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数,依次输出结果.
采用链式的then
,可以指定一组按照次序调用的回调函数.这时,前一个回调函数,有可能返回的还是一个Promise
对象(即有异步操作),这时后一个回调函数,就会等待该Promise
对象的状态发生变化,才会被调用.
3. Promise.prototype.catch 方法: (onRejected) => {}
Promise.prototype.catch()
方法是.then(null, rejection)
或.then(undefined, rejection)
的别名,用于 指定发生错误时的回调函数.
- onRejected 函数: 失败的回调函数
(reason) => {}
- 异常穿透使用:运行到最后,没被处理的所有异常错误都会进入这个方法的回调函数中
基本使用:
let p = new Promise((resolve, reject) => {
// 同步调用
// 改变promise对象的状态 失败时
reject('err');
});
// 执行 catch 方法
p.then(reason =>{
console.log(reason);
}).catch(reason => {
console.log(reason);
});
- 如果该对象状态变为
resolved
,则会调用then()
方法指定的回调函数;- 如果异步操作抛出错误,状态就会变为
rejected
,就会调用catch()
方法指定的回调函数,处理这个错误then()
方法指定的回调函数,如果运行中抛出错误,也会被catch()
方法捕获.
4. Promise.resolve 方法: (value) => {}
有时需要将现有对象转为 Promise 对象,Promise.resolve()
方法就起到这个作用.返回一个成功/失败的 promise 对象,直接改变promise状态
- 如果传入的参数为 非Promise类型的对象, 则返回的结果为成功promise对象
- 如果传入的参数为 Promise 对象, 则参数的结果决定了 resolve 的结果
// 非Promise类型
let p1 = Promise.resolve(123);
console.log(p1);
// Promise 对象
let p2 = Promise.resolve(new Promise((resolve, reject) => {
// resolve('ok');
reject('err');
}));
console.log(p2);
// 用catch传入失败的回调,Handle failed results,可解决报错
p2.catch(reason => {
console.log(reason);
});
5. Promise.reject 方法: (reason) => {}
Promise.reject(reason)
方法也会返回一个新的 Promise 实例,该实例的状态为rejected
.返回一个失败的 promise 对象,直接改变promise状态
let p1 = Promise.reject(123);
let p2 = Promise.reject('hahaha');
let p3 = Promise.reject(new Promise((resolve, reject) => {
resolve('ok')
}))
console.log(p1);
console.log(p2);
console.log(p3);
It can be seen from the code and results,传入
数字
,字符串
,resolved(成功)状态的 Promise 对象
的参数,Will eventually return to get onerejected(失败)状态的Promise对象
.
6. Promise.all 方法: (promises) => {}
Promise.all()
方法用于将多个 Promise 实例,包装成一个新的 Promise 实例.返回一个新的 promise, 只有所有的 promise 都成功才成功, 只要有一 个失败了就直接失败.
Promise.all()
方法接受一个数组作为参数- 如果不是 Promise 实例,就先调用
Promise.resolve
方法,将参数转为 Promise 实例,再进一步处理.
有一 个失败了就直接失败,代码如下:
// 有一个失败
let p1 = new Promise((resolve, reject) => {
resolve('ok1');
})
let p2 = Promise.resolve('ok2');
let p3 = Promise.resolve('ok3');
// the only one to fail
let p4 = Promise.reject('err');
let result = Promise.all([p1, p2, p3, p4]);
console.log(result);
全部成功才成功,代码如下:
// 全部成功
let p1 = new Promise((resolve, reject) => {
resolve('ok1');
})
let p2 = Promise.resolve('ok2');
let p3 = Promise.resolve('ok3');
let result = Promise.all([p1, p2, p3]);
console.log(result);
7. Promise.race 方法: (promises) => {}
Promise.race()
方法同样是将多个 Promise 实例,包装成一个新的 Promise 实例.返回一个新的 promise, 第一个完成
的 promise 的结果状态就是最终的结果状态.
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('ok1');
}, 1000);
})
let p2 = Promise.reject('err');
let p3 = Promise.resolve('ok2');
// The result is determined by the state of the first one
// 最后为rejected,err
const result = Promise.race([p1, p2, p3]);
console.log(result);
p1延时,开启了异步,Others are normally performed synchronously,所以
p2>p3>p1
,结果是P2
8. Promise.prototype.finally 方法
finally()
方法用于指定不管 Promise 对象最后状态如何,都会执行的操作.该方法是 ES2018 引入标准的.
finally
方法的回调函数不接受任何参数- Means there is no way to know,前面的 Promise 状态到底是
fulfilled
还是rejected
. - 所以,
finally
方法里面的操作,应该是与状态无关的,不依赖于 Promise 的执行结果.
promise
.then(result => {
}).catch(error => {
}).finally(() => {
});
9. Promise.any 方法
ES2021 新增了Promise.any()方法.该方法接受一组 Promise 实例作为参数,包装成一个新的 Promise 实例返回.只要参数实例有一个变成成功(fulfilled)
状态,包装实例就会变成成功(fulfilled)
状态;如果所有参数实例都变成失败(rejected)
状态,包装实例就会变成失败(rejected)
状态.
- 只要其中的一个 promise 成功,就返回那个已经成功的 promise
Promise.any()
跟Promise.race()
方法很像,只有一点不同,就是不会因为某个 Promise 变成失败(rejected)
状态而结束.
一个 Promise 成功时:
var p1 = Promise.reject('err1');
var p2 = Promise.reject('err2');
var p3 = Promise.resolve('ok1');
var result = [p1, p2, p3];
Promise.any(result).then(value => {
console.log('value: ', value)
}).catch(err => {
console.log('err: ', err)
});
The final result is only obtained第一个成功的回调
如果所有传入的 promises 都失败:
var p1 = Promise.reject('err1');
var p2 = Promise.reject('err2');
var p3 = Promise.reject('err3');
var result = [p1, p2, p3];
Promise.any(result).then(value => {
console.log('value: ', value);
}).catch(err => {
console.log('err: ', err);
console.log(err.message);
console.log(err.name);
console.log(err.errors);
});
10. Promise.allSettled 方法
ES2020 引入了Promise.allSettled()
方法,接受一组 Promise 实例作为参数,包装成一个新的 Promise 实例.只有等到所有这些参数实例都返回结果(不管是fulfilled
还是rejected
),包装实例才会结束.
- All statuses of success or failure can be obtained
- 每个对象都有
status
属性,该属性的值只可能是字符串fulfilled
或字符串rejected
. fulfilled
时,对象有value
属性,rejected
时有reason
属性,对应两种状态的返回值.
const p1 = Promise.resolve('ok1');
const p2 = Promise.reject('err1');
// 这里的Promise.allSettled Only get successful callbacks `fulfilled`
Promise.allSettled([p1, p2]).then(value=> {
console.log(value); //注意,这是 `fulfilled` 的回调函数,You can only enter here if its status is successful
});
通过上述代码可知,We only called successful callbacks,Failed callbacks are not called,But the end result is listedAll callback status
If you find it helpful, you can continue to the next article!
Promise学习(三)Promise的几个关键性问题 – 状态改变、Execution order and mechanism、多任务串联、异常穿透、中断promise链
Authors: min
时间: 2022年7月25日
边栏推荐
- pve 删除虚拟机「建议收藏」
- WPF 截图控件之绘制箭头(五)「仿微信」
- Endorsed in 2022 years inventory | product base, science and technology, guangzhou automobile group striding forward
- [Cloud Residency Co-Creation] Huawei Cloud Global Scheduling Technology and Practice of Distributed Technology
- notes....
- 图解MySQL内连接、外连接、左连接、右连接、全连接......太多了
- 使用ESP32驱动QMA7981读取三轴加速度(带例程)
- Custom Types - Enums, Unions
- 报告:想学AI的学生数量已涨200%,老师都不够用了
- 可视化——Superset安装与部署
猜你喜欢
随机推荐
C#/VB.NET 将PPT或PPTX转换为图像
2022年中盘点 | 产品打底,科技背书,广汽集团阔步向前
C#/VB.NET 将PPT或PPTX转换为图像
4种常见的鉴权方式及说明
How to find out hidden computer software (how to clean up the computer software hidden)
什么是步进电机?40张图带你了解!
ClickHouse多种安装方式
Message queue interview latest finishing (2022)
WPF 截图控件之绘制箭头(五)「仿微信」
Small application project works WeChat gourmet recipes applet graduation design of finished product (1) the development profile
STM32入门开发 介绍IIC总线、读写AT24C02(EEPROM)(采用模拟时序)
Basic configuration commands of cisco switches (what is the save command of Huawei switches)
从零开始Blazor Server(4)--登录系统
Golang内存分析工具gctrace和pprof实战
The meaning and trigger conditions of gc
ModelArts-based object detection YOLOv3 practice [play with HUAWEI CLOUD]
如何从完美的智能合约中窃取 1 亿美元
RK3399平台开发系列讲解(内核入门篇)1.52、printk函数分析 - 其函数调用时候会关闭中断
对于小应用来讲,使用哪款数据库比较好?
CTFshow,命令执行:web34、35、36