0
一文搞懂 Promise 新 Api allSettled 的用法和 all 区别,以及如何在不支持新特性的环...
source link: https://www.cnblogs.com/PeiQi1229/p/17362393.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
一文搞懂 Promise 新 Api allSettled
的用法和 all
区别,以及如何在不支持新特性的环境下实现一个 Polyfill
allSettled 的用法
const runAllSettled = async () => {
const successPromise = Promise.resolve('success') // 一个正常返回的 Promise
const failPromise = Promise.reject('fail') // 一个异常返回的 Promise
// 使用 allSettled
const settiled = await Promise.allSettled([successPromise, failPromise, undefined, null])
console.log(settiled)
/* 输出结果如下
[
{status: 'fulfilled', value: 'success'},
{status: 'rejected', reason: 'fail'},
{status: 'fulfilled', value: undefined},
{status: 'fulfilled', value: null},
]
*/
}
runAllSettled()
- 返回一个数组,每一个元素都是一个对象,里面必然包含
status
属性 status
属性只会有两个值,fulfilled
或者rejected
,非黑即白的既视感allSettled
总是走then
的,也就是并发的 Promise 出现reject
也不会走catch
,需要自行遍历返回的数组,判断status
来做错误捕获- 对象中还有另外两个属性,
value
和reason
。根据 promise 的状态返回,如果成功返回,即为value
,反之为reason
- 更详细的 TS 类型在这里
lib.es2020.promise.d.ts
all 的用法
- all 的用法就不再详细赘述,可前往 MDN 查看
功 能 | Promise.all |
Promise.allSettled |
---|---|---|
并发 | ✅ | ✅ |
并发Promise中出现 reject 是否还走 then |
❌ | ✅ |
在不支持 Promise.allSettled
新特性的环境下实现一个 Polyfill
// 通过 Promise.all 实现 Promise.allSettled
if (!Promise.allSettled) {
Promise.allSettled = function (promises) {
return Promise.all(
promises.map((p) =>
Promise.resolve(p).then(
(value) => ({
status: "fulfilled",
value,
}),
(reason) => ({
status: "rejected",
reason,
})
)
)
);
};
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK