[Javascript] Wait for Multiple JavaScript Promises to Settle with Promise.allSettled()

The Promise.allSettled() method accepts an array (or any other iterable) of promises as a parameter. It returns a Promise object that is fulfilled with an array of settlement objects. Each settlement object describes the settlement of the corresponding input promise.

Notice that the Promise object returned from the Promise.allSettled() method is only rejected if there‘s an error iterating over the input promises. In all other cases, it is fulfilled.

The Promise.allSettled() method is useful when you want to wait for multiple promises to settle, no matter whether they‘ll be fulfilled or rejected.

First thing first, let‘s understand what is promise state:

‘Settled‘ means both ‘Resolved‘ or ‘Rejected‘. So in most cases, Promise.settled() alwasy resolved. But if you do:

Promise.allSettled({}) 

It will throw error. Because {} is not iterable.

Why we need to use Promise.allSettled()?

Remeber Promise.all([..]), one promise rejected will cause the whole Promise get rejected. It is always a problem which cause a not user-friendly case.

Promise.allSettled([...]) is good a handling this case:

const API_URL = "https://starwars.egghead.training/";

const output = document.getElementById("output");
const spinner = document.getElementById("spinner");

function queryAPI(endpoint) {
  return fetch(API_URL + endpoint).then(response => {
    return response.ok
      ? response.json()
      : Promise.reject(Error("Unsuccessful response"));
  });
}

Promise.allSettled([
  queryAPI("films").then(f => `${f.length} films`),
  queryAPI("planets").then(p => `${p.length} planets`),
  queryAPI("species").then(s => `${s.length} species`),
  queryAPI("vehicles").then(v => `${v.length} vehicles`)
])
  .then(results => {
    const statistics = results
      .filter(result => result.status === "fulfilled")
      .map(result => result.value);
    output.innerText =
      statistics.length === 0
        ? "Failed to load statistics :("
        : statistics.join("\n");
  })
  .catch(error => {
    console.warn(error);
    output.innerText = ":(";
  })
  .finally(() => {
    spinner.remove();
  });

The ressuls comes back from Promise.allSettled()

原文地址:https://www.cnblogs.com/Answer1215/p/12336849.html

时间: 2024-08-28 20:24:23

[Javascript] Wait for Multiple JavaScript Promises to Settle with Promise.allSettled()的相关文章

【转】6 Reasons Why JavaScript’s Async/Await Blows Promises Away (Tutorial)

原文:https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9 ---------------------------------------------------------------------------------------------- 6 Reasons Why JavaScript's Async/Await Blows Prom

<script language = "javascript">, <script type = "text/javascript">和<script language = "application/javascript">(转)

application/javascript是服务器端处理js文件的mime类型,text/javascript是浏览器处理js的mime类型,后者兼容性更好(虽然application/javascript才是正确写法,由于现在大家都写错的,导致浏览器厂商对写application/javascript兼容性更好).等以后大家都用HTML5的时候,就不需要写这个了.直接<script></script>就OK了! 另外 <script language = "ja

javascript闭包(Effective JavaScript读书笔记)

Effective JavaScript:编写高质量JavaScript代码的68个有效方法: Item 11:   Get Comfortable with Closures Closures may be an unfamiliar concept to programmers coming from languages that don’t support them. And they may seem intimidating at first. But rest assured tha

JavaScript大杂烩6 - 理解JavaScript中的this

在JavaScript开发中,this是很常用的一个关键字,但同时也是一个很容易引入bug的一个关键字,在这里我们就专门总结一下页面中可能出现的this关键字(包括几种在其他页面文件中出现的this). JavaScript中的this关键字通常只使用在函数中,它指向当前函数的调用者,这是this关键字的本质,所有的使用方式都是围绕这个展开的,让我们来看一下在各种性质的函数中this的用法.1. 在对象的函数中使用this var person = { name: 'Frank', say: f

[Javascript] How to use JavaScript&#39;s String.replace

In JavaScript, you can change the content of a string using the replace method. This method signature is overloaded with a bunch of different ways to do string replacement in JavaScript. This lesson covers the entire API (including an interestingDSL 

如何选择Javascript模板引擎(javascript template engine)?

译者 jjfat 日期:2012-9-17  来源: GBin1.com 随着前端开发的密集度越来越高,Ajax和JSON的使用越来越频繁,大家肯定免不了在前台开发中大量的使用标签,常见到的例子如下: 你的到了一个JSON对象,如下: var data={   email: '[email protected],   gender: 'male'  } 然后你需要将json数据组织成页面内容,如下: var email, gender; email= '<div class="mail&q

【JavaScript】深入理解JavaScript之强大的原型和原型链

由于JavaScript是唯一一个被广泛使用的基于原型继承的语言,所以理解两种继承模式的差异是需要一定时间的,今天我们就来了解一下原型和原型链. AD: hasOwnProperty函数: hasOwnProperty是Object.prototype的一个方法,它可是个好东西,他能判断一个对象是否包含自定义属性而不是原型链上的属性,因为hasOwnProperty 是 JavaScript 中唯一一个处理属性但是不查找原型链的函数. // 修改Object.prototype Object.p

JavaScript 编程珠玑 - 《JavaScript: The good parts》总结(2)

一.扩展函数原型的更好办法: // 定义下面的通用方法 Function.prototype.method = function (name, func) {     this.prototype[name] = func;     return this; }; // 使用上面的通用方法作为工具进行扩展,以免每次扩展都访问Function.prototype.XXX (that's ugly). Number.method('integer', function() {     return 

JavaScript之基础-1 JavaScript(概述、基础语法)

一.JavaScript 概述 JavaScript 概念 - JavaScript 是一种运行于 JavaScript解释器/引擎中的解释型脚本语言 - JavaScript 解释器作为JS脚本的运行环境,有如下两种呈现方式 - 独立安装的 JavaScript 解释器; - 嵌入在浏览器内核中的 JavaScript 解释器; - 目前 PC .平板.手机.机顶盒中安装的主要浏览器全部支持JavaScript JavaScript 发展史 - 1992年,Nombas公司为自己的CEnvi软