Promise.allSettled & Promise.all & Promise.race & Promise.any All In One
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>
***
Promise.allSettled & Promise.all & Promise.race & Promise.any All In One的更多相关文章
- 由浅入深,从掌握Promise的基本使用到手写Promise
由浅入深,从掌握Promise的基本使用到手写Promise 前言 在ES6之前,对于一些异步任务的处理始终没有很好的方案可以解决,处理异步的方案可谓是十分混乱,在业务需求下异步请求的套用,就形成了回 ...
- Promise (1) 如何使用Promise
Promise 也是面试高频问题, 今天我们来看看Promise是什么, 能做什么, 怎么用, 下一期我们自己来模拟一个myPromise 1 Promise 是什么 我们要学会自己给自己提问, 才 ...
- promise不会被return触发, 一个promise对象中不会被Promise.reject触发
1. let a = new Promise((resolve,reject)=>{ return 23 }) a; // promise <pending> 2. let a = ...
- JS引擎是如何工作的?从调用堆栈到Promise
摘要: 理解 JS 引擎运行原理. 作者:前端小智 原文:JS引擎:它们是如何工作的?从调用堆栈到Promise,需要知道的所有内容 Fundebug经授权转载,版权归原作者所有. 为了保证可读性,本 ...
- 手写一个Promise/A+,完美通过官方872个测试用例
前段时间我用两篇文章深入讲解了异步的概念和Event Loop的底层原理,然后还讲了一种自己实现异步的发布订阅模式: setTimeout和setImmediate到底谁先执行,本文让你彻底理解Eve ...
- ES6语法——Promise对象
一.概念 Promise是异步编程的一种解决方案(解决回调地狱的问题),是一个能够获取异步操作信息的对象.Promise的内部保存着某个未来才会结束的事件(通常是一个异步操作) 二.特点 1.Prom ...
- Promise的三兄弟:all(), race()以及allSettled()
摘要: 玩转Promise. 原文:Promise 中的三兄弟 .all(), .race(), .allSettled() 译者:前端小智 Fundebug经授权转载,版权归原作者所有. 从ES6 ...
- 理解和使用Promise.all和Promise.race
一.Pomise.all的使用 Promise.all可以将多个Promise实例包装成一个新的Promise实例.同时,成功和失败的返回值是不同的,成功的时候返回的是一个结果数组,而失败的时候则返回 ...
- Promise.all和Promise.race区别,和使用场景
一.Pomise.all的使用 常见使用场景 : 多个异步结果合并到一起 Promise.all可以将多个Promise实例包装成一个新的Promise实例.用于将多个Promise实例,包装成一个新 ...
随机推荐
- apk开发环境!多亏这份《秋招+金九银十-腾讯面试题合集》跳槽薪资翻倍!再不刷题就晚了!
开头 最近很多网友反馈:自己从各处弄来的资料,过于杂乱.零散.碎片化,看得时候觉得挺有用的,但过个半天,啥都记不起来了.其实,这就是缺少系统化学习的后果. 为了提高大家的学习效率,帮大家能快速掌握An ...
- Ubuntu 能ping通DNS 地址 无法解析域名
ping通qq百度都行,唯独谷歌不行, 主机能够ping通google的dns服务器地址 8.8.8.8,却无法解析域名 $ ping www.google.co.uk ping: unknown ...
- unstable sort
$sort (aggregation) - MongoDB Manual https://docs.mongodb.com/manual/reference/operator/aggregation/ ...
- Privacy-Enhanced Mail (PEM) Privacy Enhancement for Internet Electronic Mail
小结 1. 加密基本流程 本地格式标准格式认证(填充与完整性检查)与加密可打印编码 Privacy-Enhanced Mail (PEM) RFC 2313 - PKCS #1: RSA Encryp ...
- odoo-nginx 配置
p.p1 { margin: 0; font: 12px "Andale Mono"; color: rgba(40, 254, 20, 1); background-color: ...
- LOJ10196越狱
题目描述 原题来自:HNOI 2008 监狱有连续编号为 1 到 n 的 n 个房间,每个房间关押一个犯人.有 m 种宗教,每个犯人可能信仰其中一种.如果相邻房间的犯人信仰的宗教相同,就可能发生越狱. ...
- HBase与Zookeeper的关系
HBase与Zookeeper的关系 一.HBase与Zookeeper的关系 Zookeeper Client Master RegionServer 一.HBase与Zookeeper的关系 Cl ...
- Java中详述线程间协作
线程协作 首先引入一段代码: package 线程间数据共享; import java.util.Date; public class Watch { private static String ti ...
- shell脚本的使用该熟练起来了,你说呢?(篇四)
继续前一篇的文章: shell脚本的使用该熟练起来了,你说呢?(篇一) shell脚本的使用该熟练起来了,你说呢?(篇二) shell脚本的使用该熟练起来了,你说呢?(篇三) 文章里面测试的命令脚本文 ...
- [SCOI2009] [BZOJ1026] windy数
windy定义了一种windy数.不含前导零且相邻两个数字之差至少为2的正整数被称为windy数. windy想知道, 在A和B之间,包括A和B,总共有多少个windy数?\(1 \le A \le ...