Understand the all(), race(), and allSettled() methods in Promise
Starting from ES6, we mostly use Promise.all()
and Promise.race()
, Promise. allSettled()
The proposal has reached stage 4 and will therefore become part of ECMAScript 2020
.
1. Overview
##Promise.all(promises: Iterable
- ##Promise.all(iterable)
- method returns a
Promise
instance, this instance isiterable
The callback is completed (resolve) when allpromise
in the parameters are "resolved" or the parameters do not containpromise
; ifpromise in the parameters
There is a failure (rejected), the callback of this instance fails (reject), the failure reason is the result of the first failedpromise
(promises: Iterable
- The method returns a
- promise that will be resolved or rejected once a promise
in the iterator is resolved or rejected.
Promise.allSettled
(promises: Iterable>): Promise >>
promise Promise.allSettled() method returns a- that
- promise ##promise has been resolved or resolved after being rejected, and each object describes the outcome of each
promise
.2. Review: Promise States
Given an asynchronous operation that returns a
, these are the Promise Possible states:
rejected: means the operation failed.pending: Initial state, neither success nor failure state.
fulfilled: means the operation was completed successfully.
- Settled: Promise
- Either completed or rejected. Promise
- Once achieved, its status will no longer change.
-
Also known as part-whole mode, it integrates objects into a tree structure to Represents a hierarchy of "part-whole" structures. The composition mode allows users to use single objects and composite objects consistently. It is based on two functions:
Primitive functions (short: primitives) create atomic blocks.
Composition functions (abbreviated as: composition) combine atoms and/or composites together to form composites.- For JS Promises
- The primitive functions include: Promise.resolve()
Promise.reject()
- Combined functions:
Promise.all()
,Promise.race()
, Promise.allSettled() -
4. Promise.all()
:
Promise.all
rejected(promises: Iterable<promise>>): Promise<array>><ul> <li><strong><t><t><t>##Return Situation: </t></t></t>Fulfillment: </strong></li>If the incoming iterable object is empty, </ul>Promise.all<p> will synchronously return a completed (</p>resolved<p>) status <strong>promise</strong>. <br>If all incoming <code>promise
become completed, or there is nopromise
in the incoming iterable object,Promise.all
returns
promiseBecomes fulfilled asynchronously.
In any case, the completion status result ofpromise
returned byPromise.all
is an array, which contains the values of all the incoming iteration parameter objects (including non-promise value).
Failure/Rejection:If one of the incoming
promise
fails (), Promise.all Asynchronously gives the failed result to the callback function in the failure status, regardless of whether other
promiseare completed.
Let’s take an example:
const promises = [ Promise.resolve('a'), Promise.resolve('b'), Promise.resolve('c'), ]; Promise.all(promises) .then((arr) => assert.deepEqual( arr, ['a', 'b', 'c'] ));
What happens if one of the promises is rejected:
const promises = [ Promise.resolve('a'), Promise.resolve('b'), Promise.reject('ERROR'), ]; Promise.all(promises) .catch((err) => assert.equal( err, 'ERROR' ));
The following figure illustrates
Promise.all()How it works4.1 Asynchronous.map() and Promise.all()
.map( )Array conversion methods, such as
,
, etc., used for synchronous calculation. For example.filter()
What happens if the callback offunction timesTwoSync(x) { return 2 * x; } const arr = [1, 2, 3]; const result = arr.map(timesTwoSync); assert.deepEqual(result, [2, 4, 6]);
.map()
is an array ofis a function based on
Promise? Using this method, the result returned by
.map()Promises
.
Promises
数组不是普通代码可以使用的数据,但我们可以通过Promise.all()
来解决这个问题:它将Promises数组转换为Promise
,并使用一组普通值数组来实现。function timesTwoAsync(x) { return new Promise(resolve => resolve(x * 2)); } const arr = [1, 2, 3]; const promiseArr = arr.map(timesTwoAsync); Promise.all(promiseArr) .then(result => { assert.deepEqual(result, [2, 4, 6]); });
更实际工作上关于 .map()示例
接下来,咱们使用
.map()
和Promise.all()
从Web
下载文件。 首先,咱们需要以下帮助函数:function downloadText(url) { return fetch(url) .then((response) => { // (A) if (!response.ok) { // (B) throw new Error(response.statusText); } return response.text(); // (C) }); }
downloadText()
使用基于Promise
的fetch API 以字符串流的方式下载文件:- 首先,它异步检索响应(第A行)。
- response.ok(B行)检查是否存在“找不到文件”等错误。
- 如果没有错误,使用
.text()
(第C行)以字符串的形式取回文件的内容。
在下面的示例中,咱们 下载了两个文件
const urls = [ 'http://example.com/first.txt', 'http://example.com/second.txt', ]; const promises = urls.map( url => downloadText(url)); Promise.all(promises) .then( (arr) => assert.deepEqual( arr, ['First!', 'Second!'] ));
Promise.all()的一个简版实现
function all(iterable) { return new Promise((resolve, reject) => { let index = 0; for (const promise of iterable) { // Capture the current value of `index` const currentIndex = index; promise.then( (value) => { if (anErrorOccurred) return; result[currentIndex] = value; elementCount++; if (elementCount === result.length) { resolve(result); } }, (err) => { if (anErrorOccurred) return; anErrorOccurred = true; reject(err); }); index++; } if (index === 0) { resolve([]); return; } let elementCount = 0; let anErrorOccurred = false; const result = new Array(index); }); }
5. Promise.race()
Promise.race()
方法的定义:Promise.race
(promises: Iterable >): Promise Promise.race(iterable) 方法返回一个
promise
,一旦迭代器中的某个promise
解决或拒绝,返回的promise
就会解决或拒绝。来几个例子,瞧瞧:const promises = [ new Promise((resolve, reject) => setTimeout(() => resolve('result'), 100)), // (A) new Promise((resolve, reject) => setTimeout(() => reject('ERROR'), 200)), // (B) ]; Promise.race(promises) .then((result) => assert.equal( // (C) result, 'result'));
在第
A
行,Promise
是完成状态 ,所以 第C
行会执行(尽管第B
行被拒绝)。如果 Promise 被拒绝首先执行,在来看看情况是嘛样的:
const promises = [ new Promise((resolve, reject) => setTimeout(() => resolve('result'), 200)), new Promise((resolve, reject) => setTimeout(() => reject('ERROR'), 100)), ]; Promise.race(promises) .then( (result) => assert.fail(), (err) => assert.equal( err, 'ERROR'));
注意,由于
Promse
先被拒绝,所以Promise.race()
返回的是一个被拒绝的Promise
这意味着
Promise.race([])
的结果永远不会完成。下图演示了
Promise.race()
的工作原理:Promise.race() 在 Promise 超时下的情况
在本节中,我们将使用
Promise.race()
来处理超时的Promise
。 以下辅助函数:function resolveAfter(ms, value=undefined) { return new Promise((resolve, reject) => { setTimeout(() => resolve(value), ms); }); }
resolveAfter()
主要做的是在指定的时间内,返回一个状态为resolve
的Promise
,值为为传入的value
调用上面方法:
function timeout(timeoutInMs, promise) { return Promise.race([ promise, resolveAfter(timeoutInMs, Promise.reject(new Error('Operation timed out'))), ]); }
timeout()
返回一个Promise
,该Promise
的状态取决于传入promise
状态 。其中
timeout
函数中的resolveAfter(timeoutInMs, Promise.reject(new Error('Operation timed out'))
,通过resolveAfter
定义可知,该结果返回的是一个被拒绝状态的Promise
。再来看看
timeout(timeoutInMs, promise)
的运行情况。如果传入promise
在指定的时间之前状态为完成时,timeout
返回结果就是一个完成状态的Promise
,可以通过.then
的第一个回调参数处理返回的结果。timeout(200, resolveAfter(100, 'Result!')) .then(result => assert.equal(result, 'Result!'));
相反,如果是在指定的时间之后完成,刚
timeout
返回结果就是一个拒绝状态的Promise
,从而触发catch
方法指定的回调函数。timeout(100, resolveAfter(2000, 'Result!')) .catch(err => assert.deepEqual(err, new Error('Operation timed out')));
重要的是要了解“Promise 超时”的真正含义:
- 如果传入入
Promise
较到的得到解决,其结果就会给返回的Promise
。 - 如果没有足够快得到解决,输出的
Promise
的状态为拒绝。
也就是说,超时只会阻止传入的Promise,影响输出 Promise(因为Promise只能解决一次), 但它并没有阻止传入
Promise
的异步操作。5.2 Promise.race() 的一个简版实现
以下是
Promise.race()
的一个简化实现(它不执行安全检查)function race(iterable) { return new Promise((resolve, reject) => { for (const promise of iterable) { promise.then( (value) => { if (settlementOccurred) return; settlementOccurred = true; resolve(value); }, (err) => { if (settlementOccurred) return; settlementOccurred = true; reject(err); }); } let settlementOccurred = false; }); }
6.Promise.allSettled()
“Promise.allSettled”
这一特性是由Jason Williams,Robert Pamely和Mathias Bynens提出。promise.allsettle()
方法的定义:-
Promise.allSettled
(promises: IterablePromise >)
: PromiseArray>>
它返回一个
Array
的Promise
,其元素具有以下类型特征:type SettlementObject<T> = FulfillmentObject<T> | RejectionObject; interface FulfillmentObject<T> { status: 'fulfilled'; value: T; } interface RejectionObject { status: 'rejected'; reason: unknown; }
Promise.allSettled()
方法返回一个promise,该promise在所有给定的promise已被解析或被拒绝后解析,并且每个对象都描述每个promise的结果。举例说明, 比如各位用户在页面上面同时填了3个独立的表单, 这三个表单分三个接口提交到后端, 三个接口独立, 没有顺序依赖, 这个时候我们需要等到请求全部完成后给与用户提示表单提交的情况
在多个
promise
同时进行时咱们很快会想到使用Promise.all
来进行包装, 但是由于Promise.all
的短路特性, 三个提交中若前面任意一个提交失败, 则后面的表单也不会进行提交了, 这就与咱们需求不符合.Promise.allSettled
跟Promise.all
类似, 其参数接受一个Promise
的数组, 返回一个新的Promise
, 唯一的不同在于, 其不会进行短路, 也就是说当Promise
全部处理完成后我们可以拿到每个Promise
的状态, 而不管其是否处理成功.下图说明
promise.allsettle()
是如何工作的6.1 Promise.allSettled() 例子
这是
Promise.allSettled()
使用方式快速演示示例Promise.allSettled([ Promise.resolve('a'), Promise.reject('b'), ]) .then(arr => assert.deepEqual(arr, [ { status: 'fulfilled', value: 'a' }, { status: 'rejected', reason: 'b' }, ]));
6.2 Promise.allSettled() 较复杂点的例子
这个示例类似于
.map()
和Promise.all()
示例(我们从其中借用了downloadText()
函数):我们下载多个文本文件,这些文件的url
存储在一个数组中。但是,这一次,咱们不希望在出现错误时停止,而是希望继续执行。Promise.allSettled()
允许咱们这样做:const urls = [ 'http://example.com/exists.txt', 'http://example.com/missing.txt', ]; const result = Promise.allSettled( urls.map(u => downloadText(u))); result.then( arr => assert.deepEqual( arr, [ { status: 'fulfilled', value: 'Hello!', }, { status: 'rejected', reason: new Error('Not Found'), }, ] ));
6.3 Promise.allSettled() 的简化实现
这是
promise.allsettle()
的简化实现(不执行安全检查)function allSettled(iterable) { return new Promise((resolve, reject) => { function addElementToResult(i, elem) { result[i] = elem; elementCount++; if (elementCount === result.length) { resolve(result); } } let index = 0; for (const promise of iterable) { // Capture the current value of `index` const currentIndex = index; promise.then( (value) => addElementToResult( currentIndex, { status: 'fulfilled', value }), (reason) => addElementToResult( currentIndex, { status: 'rejected', reason })); index++; } if (index === 0) { resolve([]); return; } let elementCount = 0; const result = new Array(index); }); }
7. 短路特性
Promise.all()
和romise.race()
都具有 短路特性-
Promise.all(): 如果参数中
promise
有一个失败(rejected),此实例回调失败(reject)
Promise.race():如果参数中某个
promise
解决或拒绝,返回的 promise就会解决或拒绝。8.并发性和 Promise.all()
8.1 顺序执行与并发执行
考虑下面的代码:
asyncFunc1() .then(result1 => { assert.equal(result1, 'one'); return asyncFunc2(); }) .then(result2 => { assert.equal(result2, 'two'); });
使用
.then()
顺序执行基于Promise
的函数:只有在asyncFunc1()
的结果被解决后才会执行asyncFunc2()
。而
Promise.all()
是并发执行的Promise.all([asyncFunc1(), asyncFunc2()]) .then(arr => { assert.deepEqual(arr, ['one', 'two']); });
8.2 并发技巧:关注操作何时开始
确定并发异步代码的技巧:关注异步操作何时启动,而不是如何处理它们的Promises。
例如,下面的每个函数都同时执行
asyncFunc1()
和asyncFunc2()
,因为它们几乎同时启动。function concurrentAll() { return Promise.all([asyncFunc1(), asyncFunc2()]); } function concurrentThen() { const p1 = asyncFunc1(); const p2 = asyncFunc2(); return p1.then(r1 => p2.then(r2 => [r1, r2])); }
另一方面,以下两个函数依次执行
asyncFunc1()
和asyncFunc2()
:asyncFunc2()
仅在asyncFunc1()
的解决之后才调用。function sequentialThen() { return asyncFunc1() .then(r1 => asyncFunc2() .then(r2 => [r1, r2])); } function sequentialAll() { const p1 = asyncFunc1(); const p2 = p1.then(() => asyncFunc2()); return Promise.all([p1, p2]); }
8.3 Promise.all() 与 Fork-Join 分治编程
Promise.all()
与并发模式“fork join”松散相关。重温一下咱们前面的一个例子:Promise.all([ // (A) fork downloadText('http://example.com/first.txt'), downloadText('http://example.com/second.txt'), ]) // (B) join .then( (arr) => assert.deepEqual( arr, ['First!', 'Second!'] ));
- Fork:在
A
行中,分割两个异步任务并同时执行它们。 - Join:在
B
行中,对每个小任务得到的结果进行汇总。
英文原文:https://2ality.com/2019/08/promise-combinators.html
更多编程相关知识,请访问:编程教学!!
- promise ##promise has been resolved or resolved after being rejected, and each object describes the outcome of each
The above is the detailed content of Understand the all(), race(), and allSettled() methods in Promise. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools