brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Promise.allSettled waits for every promise, even the ones that fail

Javascript
~/tips/tip-javascript-promise-allsettled

const results = await Promise.allSettled([

Runs several promises together and returns the outcome of each, without stopping at the first rejection.

Promise.all gives up the moment one promise rejects, and you lose the results of the others. When the tasks are independent, that is rarely what I want.

const results = await Promise.allSettled([
  fetch("/api/a"),
  fetch("/api/b"),
  fetch("/api/c"),
]);

const failed = results.filter((r) => r.status === "rejected");

The returned promise never rejects. It fulfills once every input has settled, with an array in the same order as the inputs, whichever finished first. Each entry is an object. A success looks like { status: "fulfilled", value } and a failure like { status: "rejected", reason }. The value key only exists for the first kind and reason for the second.

That makes it a good fit for a page that loads several widgets: show the ones that arrived and a small error for the ones that did not.

MDN’s rule of thumb is to use allSettled when the tasks are independent and you want each outcome, and Promise.all when the tasks depend on each other or you want to reject at once. It has been supported in browsers since July 2020.

The caveat is that a rejected result does not throw. If you forget to look at the status, failures pass quietly, and a fetch that got a 404 counts as fulfilled anyway, because the promise resolved. Check response.ok as well.

Further reading: MDN: Promise.allSettled()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link