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:
const promise_a = new Promise((resolve) => { setTimeout(() => { resolve('Loaded Textures'); }, 3000); }); const promise_b = new Promise((resolve) => { setTimeout(() => { resolve('Loaded Music'); }, 2000); }); const promise_c = new Promise((resolve) => { setTimeout(() => { resolve('Loaded Dialogues'); }, 4000); }); const promises = [ promise_a, promise_b, promise_c ]; console.log('Hello, Promises!'); Promise.all(promises).then((values) => { console.log(values); console.log('Start the Game!'); }); /* Output 19:32:06 Hello, Promises! 19:32:10 Array(3) [ "Loaded Textures", "Loaded Music", "Loaded Dialogues" ] 19:32:10 Start the Game! */
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:
const promise_a = new Promise((resolve) => { setTimeout(() => { resolve('Loaded Textures'); }, 3000); }); const promise_b = new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('Could Not Load Music')); }, 2000); }); const promise_c = new Promise((resolve) => { setTimeout(() => { resolve('Loaded Dialogues'); }, 4000); }); const promises = [ promise_a, promise_b, promise_c ]; console.log('Hello, Promises!'); Promise.all(promises).catch((error) => { console.error(error.message); console.log('Stop the Game!'); }); /* Output 20:03:43 Hello, Promises! 20:03:45 Could Not Load Music 20:03:45 Stop the Game! */
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:
function create_promise(data, duration) { return new Promise((resolve) => { setTimeout(() => { resolve(data); }, duration); }); } const promise_a = create_promise("Loaded Textures", 3000); const promise_b = create_promise("Loaded Music", 2000); const promise_c = create_promise("Loaded Dialogue", 4000); const my_promises = [promise_a, promise_b, promise_c]; async function result_from_promises(promises) { let loading_status = await Promise.all(promises); console.log(loading_status); } result_from_promises(my_promises); /* Outputs 08:50:43 Hello, Promises! 08:50:47 Array(3) [ "Loaded Textures", "Loaded Music", "Loaded Dialogue" ] */
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.
function create_promise(city) { let random_number = Math.random(); let duration = Math.floor(Math.random()*5)*1000; return new Promise((resolve, reject) => { if (random_number < 0.8) { setTimeout(() => { resolve(`Show weather in ${city}`); }, duration); } else { setTimeout(() => { reject(`Data unavailable for ${city}`); }, duration); } }); } const promise_a = create_promise("Delhi"); const promise_b = create_promise("London"); const promise_c = create_promise("Sydney"); const my_promises = [create_promise("Delhi"), create_promise("London"), create_promise("Sydney"), create_promise("Rome"), create_promise("Las Vegas")]; async function result_from_promises(promises) { let loading_status = await Promise.allSettled(promises); console.log(loading_status); } result_from_promises(my_promises); /* Outputs [ { "status": "fulfilled", "value": "Show weather in Delhi" }, { "status": "fulfilled", "value": "Show weather in London" }, { "status": "fulfilled", "value": "Show weather in Sydney" }, { "status": "rejected", "reason": "Data unavailable for Rome" }, { "status": "fulfilled", "value": "Show weather in Las Vegas" } ] */
如您所见,数组中的每个对象都包含一个 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!

jQuery引用方法详解:快速上手指南jQuery是一个流行的JavaScript库,被广泛用于网站开发中,它简化了JavaScript编程,并为开发者提供了丰富的功能和特性。本文将详细介绍jQuery的引用方法,并提供具体的代码示例,帮助读者快速上手。引入jQuery首先,我们需要在HTML文件中引入jQuery库。可以通过CDN链接的方式引入,也可以下载

标题:闭包引起的内存泄漏及解决方法引言:闭包是JavaScript中一个非常常见的概念,它可以让内部函数访问外部函数的变量。然而,闭包在使用不当的情况下可能导致内存泄漏。本文将探讨闭包引起的内存泄漏问题,并提供解决方法及具体代码示例。一、闭包引起的内存泄漏问题闭包的特性是内部函数可以访问外部函数的变量,这意味着在闭包中引用的变量不会被垃圾回收。如果使用不当,

前端工程师职责解析:主要做什么工作?随着互联网的快速发展,前端工程师作为一个非常重要的职业角色,扮演着连接用户与网站应用程序的桥梁,起着至关重要的作用。那么,前端工程师主要做些什么工作呢?本文将对前端工程师的职责进行解析,让我们来一探究竟。一、前端工程师的基本职责网站开发与维护:前端工程师负责网站的前端开发工作,包括编写网站的HTML、CSS和JavaScr

掌握JavaScript中的图像处理和计算机视觉,需要具体代码示例随着互联网的普及和技术的进步,图像处理和计算机视觉逐渐成为了许多开发者和研究人员感兴趣的领域。而作为一种广泛应用的编程语言,JavaScript提供了许多强大的工具和库,可以帮助我们实现图像处理和计算机视觉相关的任务。本文将介绍一些常用的JavaScript库和具体的代码示例,帮助读者快速掌握

掌握JavaScript中的数据可视化和报表生成,需要具体代码示例现如今,数据可视化和报表生成已经成为了信息时代中不可或缺的一部分。无论是企业决策分析、市场营销推广还是科学研究,都需要将庞大而复杂的数据通过直观的可视化手段进行展示和分析。而JavaScript作为一种广泛应用于web开发的编程语言,具备丰富的数据可视化和报表生成库,极大地方便了开发人员对数据

本教程将教您如何在JavaScript中使用Promise等待。在本教程中,我将教您有关Promise.all()和Promise.allSettled()方法以及如何使用它们来处理多个Promise。使用Promise.all()方法Promise对象具有三个有用的方法,名为then()、catch()和finally(),您可以使用它们在Promise完成时执行回调方法。Promise.all()方法是一个静态方法,这意味着它属于整个类,而不是绑定到该类的任何特定实例。它接受可迭代的Prom

jQuery是一个流行的JavaScript库,用于简化JavaScript编程。它提供了丰富的功能和方法,包括向HTML元素中动态添加元素的功能。本文将介绍如何使用jQuery来向div中动态添加元素,同时提供具体的代码示例。首先,我们需要在HTML文档中引入jQuery库。可以通过以下方式引入:

jQuery库的分类及特点解析jQuery是一个流行的JavaScript库,它简化了JavaScript编程,提供了丰富的API和简洁的语法,被广泛用于网页开发中。本文将对jQuery库进行分类及特点解析,并通过具体代码示例来展示其灵活和强大的特性。一、分类核心jQuery库:包括基本的选择器、DOM操作、事件处理、动画等功能,是jQuery库的核心部分。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
