Promise.allSettled & Promise.all & Promise.race & Promise.any All In One
new Promise(), Promise.resolve(), Promise.reject(),
Promise.prototype.catch()
Promise.prototype.finally()
Promise.prototype.then()
Promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});
Promise.all
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
要么全部 promise 结果都成功了,返回全部的 promise 构成的一个结果值的数组;
要么只要有一个 promise 失败了,就返回失败了的 promise 的 error 值,默认 undefined
一句话总结: 全部 promise 结果都成功了,返回一个有所有成功的结果值的数组; 只要有一个promise 失败了,就的返回失败结果;
// declare function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number;
const log = console.log;
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 0, 'foo');
});
const promise4 = Promise.reject(`error message`);
Promise
.all([promise1, promise2, promise3, promise4])
.then(values => {
console.log(values);
}, err => {
console.log(`❌ promise error =`, err);
});
// ❌ promise error = error message
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values);
});
// [ 3, 42, 'foo']
const promiseFunction = async () => {
const resolvingPromise = new Promise(resolve => setTimeout(() => resolve('success'), 1000));
const rejectingPromise = new Promise((resolve, reject) => setTimeout(() => reject('fail'), 500));
try {
const allPromises = await Promise.all([resolvingPromise, rejectingPromise]);
} catch (e) {
// e is 'fail', which is the contents of the reject function from rejectingPromise
// resolvingPromise = Promise {<pending>}
console.log(e);
}
};
promiseFunction();
Promise.allSettled
返回全部的 promise 的结果,无论 promise 结果是成功还是失败,构成一个可迭代的数组对象
成功的 promise 返回一个有 status: 'fulfilled' 和 value 构成的对象
失败的 promise 返回一个有 status: 'rejected' 和 reason 构成的对象
一句话总结: 无论 promise 是成功了还是失败了, 最终都返回一个有 status 和 value 或 reason 构成的对象数组;
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
const log = console.log;
const promise1 = Promise.resolve(1);
// const promise2 = new Promise((resolve, reject) => setTimeout(reject, 0, '❌ Error'));
// const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 0, '✅ OK'));
const promise2 = Promise.reject('❌ Error');
const promise3 =Promise.resolve('✅ OK');
const promises = [promise1, promise2, promise3];
Promise.allSettled(promises). then(
(results) => results.forEach(result => log(`result`, result.status, result))
);
/*
result fulfilled {status: "fulfilled", value: 1}
result rejected {status: "rejected", reason: "❌ Error"}
result fulfilled {status: "fulfilled", value: "✅ OK"}
Promise {<fulfilled>: undefined}
*/
// [
// { status: 'fulfilled', value: 3 },
// { status: 'fulfilled', value: 42 },
// { status: 'fulfilled', value: 'foo' },
// { status: 'rejected', reason: '❌ error message' }
// ]
// declare function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number;
const log = console.log;
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 0, 'foo');
});
const promise4 = Promise.reject(`❌ error message`);
Promise
.allSettled([promise1, promise2, promise3, promise4])
.then(values => {
console.log(values);
}, err => {
console.log(`promise error =`, err);
});
// [
// { status: 'fulfilled', value: 3 },
// { status: 'fulfilled', value: 42 },
// { status: 'fulfilled', value: 'foo' },
// { status: 'rejected', reason: '❌ error message' }
// ]
Promise.allSettled([promise1, promise2, promise3]).then((values) => {
console.log(values);
});
// [
// { status: 'fulfilled', value: 3 },
// { status: 'fulfilled', value: 42 },
// { status: 'fulfilled', value: 'foo' }
// ]
const promiseFunction = async () => {
const resolvingPromise = new Promise(resolve => setTimeout(() => resolve('success'), 1000));
const rejectingPromise = new Promise((resolve, reject) => setTimeout(() => reject('fail'), 500));
try {
const allPromises = await Promise.allSettled([resolvingPromise, rejectingPromise]);
console.log(allPromises);
// allPromises
// [
// {status: "fulfilled", value: 'success'},
// {status: "rejected", reason: 'fail'}
// ]
} catch (e) {
// this code block is never executed
console.log(e);
}
};
promiseFunction();
Promise.race
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race
返回第一个完成的 promise, 不论 promise 是成功了,还是失败了; 强调的是第一个完成的 promise ✅
一句话总结: 无论 promise 是成功了还是失败了, 返回第一个完成的 promise;
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, 'one');
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'two');
});
const promise3 = new Promise((resolve, reject) => {
setTimeout(reject, 0, 'three ❌');
});
Promise.race([promise1, promise2]).then((value) => {
console.log(value);
// promise2 is faster
});
// "two"
Promise.race([promise1, promise2, promise3]).then((value) => {
console.log(value);
}, (error) => {
console.log(`error =`, error);
// reject, promise3 is fastest
});
// "error =" "three ❌"
```
```js
const promiseFunction = async () => {
const resolvingPromise = new Promise(resolve => setTimeout(() => resolve('success'), 1000));
const resolvingPromiseTwo = new Promise((resolve, reject) => setTimeout(() => resolve('successTwo'), 500));
try {
const racedPromises = await Promise.race([resolvingPromise, resolvingPromiseTwo]);
console.log(racedPromises);
// both promises would've resolved, but resolvingPromiseTwo was faster, so racedPromises = 'successTwo'`
} catch (e) {
// this code block is only executed if the first promise to settle rejects/throws
console.log(e);
}
};
promiseFunction();
```
## Promise.any
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any
如果有多个 promise 成功了,就返回最快的哪一个 promise 的值, 不管是否存在 reject 的 promise ;
如果所有的 promise 都失败了,就返回一个 聚合错误 AggregateError,Error 的新子类;
一句话总结: 如果存在成功的 promise,就返回最快的哪一个 promise 的值;如果所有的 promise 都失败了, 就返回一个聚合错误;
```js
const promise1 = Promise.reject(0);
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'quick'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 200, 'slow'));
const promises = [promise1, promise2, promise3];
Promise.any(promises).then((value) => console.log(value));
// "quick"
const promise11 = Promise.reject(0);
const promise22 = new Promise((resolve, reject) => setTimeout(reject, 100, 'quick'));
const promise33 = new Promise((resolve, reject) => setTimeout(reject, 200, 'slow'));
const promise44 = new Promise((resolve, reject) => setTimeout(resolve, 300, 'very slow'));
const promises2 = [promise11, promise22, promise33];
// const promises2 = [promise11, promise22, promise33, promise44];
Promise.any(promises2).then((value) => console.log(value), (error) => console.log(`error =`, error));
// "error =" AggregateError: All promises were rejected
// "very slow"
```
> AggregateError 聚合错误
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/AggregateError
## refs
https://www.yuque.com/sunluyong/interview/ars1bd
https://blog.jonlu.ca/posts/promises
***
<div>
<a href="https://info.flagcounter.com/QIXi"><img src="https://s11.flagcounter.com/count2/QIXi/bg_000000/txt_00FF00/border_FF00FF/columns_3/maxflags_12/viewers_0/labels_1/pageviews_1/flags_0/percent_0/" alt="Flag Counter" border="0"></a>
</div>
***
<blockquote style="display: flex; flex-flow: column; align-items: center; justify-content: center; text-align: center; border: none;">
<h3><strong><span style="font-size: 16pt; color: #00ff00;">©xgqfrms 2012-<span data-uid="copyright-aside">2020</span></strong></span</h3>
<p><span style="font-size: 18pt; color: #00ff00;"><strong>www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!</strong></span></p>
</blockquote>
***