More JavaScript answers

by Danny
Published 2 min read

All four combine several promises into one, but they settle differently on success and failure. Learn what each returns and which one to pick for your case.

The short answer

#

All four take a list of promises and return one promise. They differ in when that promise settles and what it gives you:

  • Promise.all: waits for every promise to fulfil. Rejects as soon as any one rejects.
  • Promise.allSettled: waits for every promise to finish, whatever happens. Never rejects.
  • Promise.any: fulfils with the first promise to fulfil. Rejects only if all of them reject.
  • Promise.race: settles the same way as the first promise to settle, success or failure.

_10
const [user, posts] = await Promise.all([loadUser(id), loadPosts(id)]);

Why it happens

#

When you start several async tasks at once, you have to decide what "done" means. Do you need every result, or just one? Should a single failure stop everything? Each combinator answers those questions differently, and choosing the wrong one leads to lost errors or hanging pages.

None of them cancel the other promises. When Promise.all rejects early, the other requests keep running in the background; their results are just ignored. Use an AbortController if you need to stop them.

How to fix it

#

Promise.all: you need every result

Use it when the results depend on each other and one failure means the whole task has failed, such as loading the data a page cannot render without.


_10
try {
_10
const [user, settings] = await Promise.all([loadUser(), loadSettings()]);
_10
render(user, settings);
_10
} catch (error) {
_10
showError(error); // the first rejection
_10
}

The results come back in the same order as the input, not the order they finished.

Promise.allSettled: you want every outcome

Use it when tasks are independent and you want to report on each one, such as uploading a batch of files.


_10
const results = await Promise.allSettled(files.map(upload));
_10
_10
const failed = results
_10
.map((result, index) => ({ result, file: files[index] }))
_10
.filter(({ result }) => result.status === 'rejected');
_10
_10
for (const { file, result } of failed) {
_10
console.warn(`${file.name} failed`, result.reason);
_10
}

Each result is an object with a status of 'fulfilled' and a value, or 'rejected' and a reason.

Promise.any: the first success is enough

Use it when several sources can provide the same thing and you want the fastest one that works, such as mirrors or fallback endpoints.


_10
try {
_10
const response = await Promise.any([
_10
fetch('https://cdn-a.example.com/data.json'),
_10
fetch('https://cdn-b.example.com/data.json'),
_10
]);
_10
console.log(await response.json());
_10
} catch (error) {
_10
// AggregateError: every promise rejected
_10
console.error(error.errors);
_10
}

Promise.race: the first to finish, either way

Use it when the first outcome wins even if it is an error. The classic use is a timeout, although AbortSignal.timeout is now the better tool for fetch.


_10
function timeout(ms) {
_10
return new Promise((_, reject) =>
_10
setTimeout(() => reject(new Error('Timed out')), ms),
_10
);
_10
}
_10
_10
const result = await Promise.race([slowTask(), timeout(5000)]);

Common pitfalls

#
  • Expecting Promise.all to stop the other tasks after a failure. It does not cancel anything.
  • Using Promise.all for independent tasks, so one failure hides every successful result. Use allSettled instead.
  • Mixing up any and race. race settles on the first rejection too; any ignores rejections until all have failed.
  • Passing an empty array. Promise.all([]) and allSettled([]) fulfil straight away, any([]) rejects with an AggregateError, and race([]) never settles.
  • Awaiting promises one by one in a loop when they do not depend on each other. Start them together and combine them.
#

Was this resource helpful?