Home > Web Front-end > JS Tutorial > Explorando Promises: .all vs .allSettled / .race vs .any

Explorando Promises: .all vs .allSettled / .race vs .any

Patricia Arquette
Release: 2024-11-19 09:25:02
Original
973 people have browsed it

Promises emerged in 2015, with the release of the ECMAScript 6 (ES2015) JavaScript specification, to make our experience as a developer less complicated when dealing with asynchronous operations.

If you study or work with JavaScript, you've probably already used a Promise.all() or a Promise.race() out there. And to make life even easier for developers, with the release of more current versions of JavaScript, we have access to two new Promises methods: Promise.allSettled() and Promise.any() (ES11 and ES2021, respectively).

But what is the difference between them and when should we use each one?

Summary

Promise.all vs Promise.allSettled: focus on the result
Promise.race vs Promise.any: focus on speed

Explorando Promises: .all vs .allSettled / .race vs .any


Promise.all vs Promise.allSettled: focus on the result

Imagine that you are developing an application that, at a certain point, needs to execute different API calls. If these calls are independent of each other, a good option would be to execute all calls simultaneously, improving the application's performance, in addition to making the code more concise.

Promise.all()

  • Receives an array of Promises as argument;
  • Executes operations simultaneously (in parallel);
  • Resolve when all Promises are resolved successfully;
  • Immediately rejects if one of the Promises fails, blocking the execution of the following Promises.
async function buscarDadosParalelo() {  
  const [usuarios, produtos] = await Promise.all([
    fetch('/api/usuarios').then(resp => resp.json()),
    fetch('/api/produtos').then(resp => resp.json()),
  ]);

  return { usuarios, produtos };
}
Copy after login
Copy after login

Promise.all() is very useful when you need to ensure that all Promises are successful and the function receives all the results it needs before performing some other action.

Promise.allSettled()

  • Also receives an array of Promises as an argument;
  • Also executes operations simultaneously (in parallel);
  • Resolves when all Promises complete their execution, whether successful or failed, returning an object for each Promise containing its status (fulfilled or rejected);
  • Never rejects and, consequently, does not block the execution of Promises.
async function buscarDadosParaleloComFalhas() {   
  const resultados = await Promise.allSettled([
    fetch('/api/usuarios').then(resp => resp.json()),
    fetch('/api/produtos').then(resp => resp.json()),
  ]);

    // Verificar cada resultado individualmente:
  const dados = resultados.map(resultado => {
    if (resultado.status === 'fulfilled') {
      return resultado.value;
    } else {
      console.error(resultado.reason);
      return null;
    }
  });

  return dados;
}
Copy after login
Copy after login

Promise.allSettled() does not block the application if any Promise ends with failure, in addition to allowing individual treatment of the success or error of each call. It is like a status report, which waits for all requests to be resolved or rejected and allows the user to evaluate and handle each case.

Return to summary


Promise.race vs Promise.any: focus on speed

On the other hand, when we talk about Promise.race() and Promise.any(), we are talking about approaches to handle the first response in a set of asynchronous operations.

Promise.race()

  • Win an array of scripted Promises;
  • Executes operations simultaneously (in parallel);
  • Returns the first Promise that is completed OR rejected.
async function buscarDadosParalelo() {  
  const [usuarios, produtos] = await Promise.all([
    fetch('/api/usuarios').then(resp => resp.json()),
    fetch('/api/produtos').then(resp => resp.json()),
  ]);

  return { usuarios, produtos };
}
Copy after login
Copy after login

Promise.race() is very useful when we need a quick response — the first available return, regardless of whether it is success or error. It is also widely used with timeouts, as in the example above, to ensure that we have any response within a time limit and can prevent slow requests from continuing to consume resources.

Promise.any()

  • You also get an array of scripted Promises;
  • Executes operations simultaneously (in parallel);
  • Returns the first Promise that is completed successfully, ignoring rejections;
  • Only rejects if all Promises are rejected.
async function buscarDadosParaleloComFalhas() {   
  const resultados = await Promise.allSettled([
    fetch('/api/usuarios').then(resp => resp.json()),
    fetch('/api/produtos').then(resp => resp.json()),
  ]);

    // Verificar cada resultado individualmente:
  const dados = resultados.map(resultado => {
    if (resultado.status === 'fulfilled') {
      return resultado.value;
    } else {
      console.error(resultado.reason);
      return null;
    }
  });

  return dados;
}
Copy after login
Copy after login

Promise.any() is useful when you need at least one of the requests to complete successfully, being ideal for fallbacks and redundancies, how to load a resource from multiple sources (CDN, local, etc.) or connect to different servers in case of failure.

Return to summary


Explorando Promises: .all vs .allSettled / .race vs .any

In an increasingly asynchronous digital world, understanding how to manage multiple simultaneous operations in JavaScript has become an essential skill for developers. In this article, we explore some important Promises methods with some examples, showing how each of them works and, more importantly, when and why you should choose one over the other.

See you next time (and I promiseI'll be back soon)!

The above is the detailed content of Explorando Promises: .all vs .allSettled / .race vs .any. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template