zoukankan      html  css  js  c++  java
  • [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("
    ");
      })
      .catch(error => {
        console.warn(error);
        output.innerText = ":(";
      })
      .finally(() => {
        spinner.remove();
      });

    The ressuls comes back from Promise.allSettled()

  • 相关阅读:
    2017-2018-2 20179306 《网络攻防技术》第九周作业
    2017-2018-2 20179306 《网络攻防技术》第八周作业
    2017-2018-2 20179306《网络攻防技术》第七周作业
    2017-2018-2 20179306《网络攻防技术》第六周作业
    2017-2018-2 20179306《网络攻防技术》第五周作业
    jcFeather Maya 羽毛插件
    JCFeather 开源
    获取exr图片上像素点的颜色通道
    春天来了,看小夜游!
    jcFeather For Maya 2012免费版
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12336849.html
Copyright © 2011-2022 走看看