Home > Article > Web Front-end > Explorando Promises: .all vs .allSettled / .race vs .any
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?
Promise.all vs Promise.allSettled: focus on the result
Promise.race vs Promise.any: focus on speed
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.
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 }; }
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.
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; }
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
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.
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 }; }
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.
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; }
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
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!