码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-02-20 20:09:40      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:rip   for   moment   tle   poi   fas   sed   style   rabl   

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("\n");
}

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()

标签:rip   for   moment   tle   poi   fas   sed   style   rabl   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!