Using Promise.all() and Promise.allSettled() methods in JavaScript
This tutorial will teach you how to use Promise await in JavaScript.
In this tutorial, I will teach you about the Promise.all()
and Promise.allSettled()
methods and how to use them to handle multiple Promises.
Use Promise.all()
method
The Promise
object has three useful methods named then()
, catch()
and finally()
, You can use them to execute callback methods when the Promise completes. p>
Promise.all()
The method is a static method, which means that it belongs to the entire class and is not bound to any specific instance of the class. It accepts an iterable of Promise as input and returns a single Promise
object.
As I mentioned before, the Promise.all()
method returns a new Promise. If all promises passed to this method have resolved successfully, this new promise will resolve to an array of determined promise values. Once one of the passed promises is rejected, this new promise will also be rejected.
All Promises were resolved successfully
The following is an example of the Promise.all()
method where all Promises are resolved successfully:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
The statement before we call the Promise.all()
method was recorded at 19:32:06. Additionally, our third Promise named promise_c
takes the longest to resolve and resolves after 4 seconds. This means that the Promise returned by calling the all()
method should also take 4 seconds to resolve. We can verify if it takes 4 seconds to resolve by passing the callback function to the then()
method.
Another important thing to note here is that the returned array of completed values contains the values in the same order in which we passed the Promise to the Promise.all()
method. The Promise named promise_b
is the fastest to resolve, taking only 2 seconds. However, its parsed value is still at the second position in the returned array. This matches where we passed the Promise to the Promise.all()
method.
The maintenance of this order can be very helpful in some situations. For example, let's say you are using ten different Promises to get weather information about ten different cities. All these problems will not be solved simultaneously, and it is impossible to know in advance the order in which they will be solved. However, if you know that the data is returned in the order in which the Promise was passed, you will be able to correctly allocate it for later operations.
A promise rejected
The following is an example of one of the promises being rejected:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
Similarly, our statement before calling the all()
method is recorded at 20:03:43. However, our second promise promise_b
ended in rejection this time. We can see promise_b
is rejected after 2 seconds. This means that the Promise returned by the all()
method should also be rejected after 2 seconds with the same error as our promise_b
. It's obvious from the output that this is exactly what happens.
Used with the await
keyword
You may already know that the await
keyword is used to wait for a promise to resolve before proceeding to the next step. We also know that the all()
method returns a promise. This means we can use await
along with a call to the Promise.all()
method.
The only thing to remember is that since await
only works inside async functions and modules, we have to wrap the code inside an async function like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
This time, we define a function called create_promise()
which creates a promise for us based on the data and duration provided. Our asynchronous result_from_promises()
function uses the await
keyword to wait for a Promise to resolve.
Use Promise.allSettled()
method
It makes sense to use the Promise.all()
method when you only want to proceed after all promises have resolved successfully. This might be useful, for example, when you're loading game assets.
But suppose you are getting information about the weather in different cities. In this case, you can output weather information for all cities where data acquisition was successful, and output an error message if data acquisition failed.
Promise.allSettled()
method works best in this case. This method waits for all passed commitments to be resolved via resolution or rejection. The Promise returned by this method contains an array of objects containing information about the result of each Promise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
|
如您所见,数组中的每个对象都包含一个 status
属性,让我们知道承诺是否已实现或被拒绝。在履行承诺的情况下,它包含 value
属性中的解析值。在被拒绝的 Promise 的情况下,它在 reason
属性中包含拒绝的原因。
最终想法
我们了解了 Promise
类的两个有用方法,它们可以让您同时处理多个 Promise。当您想要在其中一个 Promise 被拒绝后立即停止等待其他 Promise 解决时, Promise.all()
方法很有用。当您想要等待所有承诺解决时,无论其解决或拒绝状态如何, Promise.allSettled()
方法非常有用。
The above is the detailed content of Using Promise.all() and Promise.allSettled() methods in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

Title: Memory leaks caused by closures and solutions Introduction: Closures are a very common concept in JavaScript, which allow internal functions to access variables of external functions. However, closures can cause memory leaks if used incorrectly. This article will explore the memory leak problem caused by closures and provide solutions and specific code examples. 1. Memory leaks caused by closures The characteristic of closures is that internal functions can access variables of external functions, which means that variables referenced in closures will not be garbage collected. If used improperly,

Mastering image processing and computer vision in JavaScript requires specific code examples. With the popularity of the Internet and the advancement of technology, image processing and computer vision have gradually become areas of interest to many developers and researchers. As a widely used programming language, JavaScript provides many powerful tools and libraries that can help us achieve image processing and computer vision-related tasks. This article will introduce some commonly used JavaScript libraries and specific code examples to help readers quickly master

Analysis of front-end engineer responsibilities: What is the main job? With the rapid development of the Internet, front-end engineers play a very important professional role, playing a vital role as a bridge between users and website applications. So, what do front-end engineers mainly do? This article will analyze the responsibilities of front-end engineers, let us find out. 1. Basic responsibilities of front-end engineers Website development and maintenance: Front-end engineers are responsible for the front-end development of the website, including writing the website’s HTML, CSS and JavaScr

Mastering data visualization and report generation in JavaScript requires specific code examples. Today, data visualization and report generation have become an indispensable part of the information age. Whether it is corporate decision-making analysis, marketing promotion or scientific research, large and complex data need to be displayed and analyzed through intuitive visualization methods. As a programming language widely used in web development, JavaScript has rich data visualization and report generation libraries, which greatly facilitates developers to analyze data.

jQuery is a well-known JavaScript library that provides simple and powerful functions to simplify JavaScript programming. When introducing jQuery into your web project, you need to add the following code to the HTML file to introduce the necessary packages: My Web Page

jQuery is a popular JavaScript library used to simplify JavaScript programming. It provides a rich set of features and methods, including the ability to dynamically add elements to HTML elements. This article will introduce how to use jQuery to dynamically add elements to divs, and provide specific code examples. First, we need to introduce the jQuery library into the HTML document. It can be introduced in the following ways:

This tutorial will teach you how to use Promise awaits in JavaScript. In this tutorial, I will teach you about Promise.all() and Promise.allSettled() methods and how to use them to handle multiple Promises. Using the Promise.all() method Promise objects have three useful methods named then(), catch(), and finally(), which you can use to execute callback methods when the Promise is completed. The Promise.all() method is a static method, which means that it belongs to the entire class and is not bound to any specific instance of the class. It accepts an iterable Prom
