[Javascript] Wait for the Fastest JavaScript Promise to Be Fulfilled with Promise.any()

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Javascript] Wait for the Fastest JavaScript Promise to Be Fulfilled with Promise.any()相关的知识,希望对你有一定的参考价值。

The Promise.any() method accepts an array (or any other iterable) of promises as a parameter. It returns a Promise object that is fulfilled with the value of the first input promise to fulfill:

  • As soon as any input promise is fulfilled, the returned Promise object is fulfilled with that value.
  • If all input promises are rejected, the returned Promise object is rejected with an AggregateError which has an errors property containing an array of all rejection reasons.

Promise.any() can be used to race multiple promises against each other and find the first promise to be fulfilled.

Please note that at the moment, the Promise.any() method is only implemented in Firefox Nightly. Make sure to use a polyfill in your application to make it work across browsers.

 

const API_URL_1 = "https://starwars.egghead.training/";
const API_URL_2 = "https://swapi.mariusschulz.com/";

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

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

function queryAPI(endpoint) {
  return Promise.any([
    query(API_URL_1, endpoint),
    query(API_URL_2, endpoint)
  ]).catch(() => {
    return Promise.reject(
      Error(`Failed to fetch endpoint "${endpoint}"`)
    );
  });
}

function getFilmTitles(films) {
  return films
    .slice()
    .sort((a, b) => a.episode_id - b.episode_id)
    .map(film => `${film.episode_id}. ${film.title}`)
    .join("
");
}

queryAPI("films")
  .then(films => {
    output.innerText = getFilmTitles(films);
  })
  .catch(error => {
    console.warn(error);
    output.innerText = ":(";
  })
  .finally(() => {
    spinner.remove();
  });

 

以上是关于[Javascript] Wait for the Fastest JavaScript Promise to Be Fulfilled with Promise.any()的主要内容,如果未能解决你的问题,请参考以下文章

[Javascript Crocks] Compose Functions for Reusability with the Maybe Type

Cursor: Pin S Wait On X In The Top 5 Wait Events

(The application/json Media Type for JavaScript Object Notation (JSON))RFC4627-JSON格式定义

About the diffrence of wait timed_wait and block in java

15ES6 for Humans: The Latest Standard of JavaScript: ES2015 and Beyond

做正确的事情,等着被开除(Do the right thing, Wait to get fired)