Promise.allSettled Narrows Settled Results

Promise.allSettled never rejects as a whole: each result carries a status discriminant, narrowing to value on fulfilled and unknown reason on rejected.

TypescriptData Fetching

Code

typescriptsnippet
24 lines
type Weather = { celsius: number };

const load = (id: string): Promise<Weather> =>
  id === 'bad' ? Promise.reject(new Error('station offline')) : Promise.resolve({ celsius: 21 });

// allSettled 不会整体 reject:每个结果都带 status 判别字段
async function main() {
  const settled = await Promise.allSettled([load('a'), load('bad'), load('c')]);

  for (const result of settled) {
    if (result.status === 'fulfilled') {
      // 收窄为 PromiseFulfilledResult<Weather>:value 可用
      console.log('ok:', result.value.celsius);
    } else {
      // 收窄为 PromiseRejectedResult:reason 是 unknown
      console.log(
        'failed:',
        result.reason instanceof Error ? result.reason.message : String(result.reason),
      );
    }
  }
}

main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ok: 21
failed: station offline
ok: 21

What the code does

load('bad') is the seeded rejection (station offline), and main awaits Promise.allSettled over three loads, branching on result.status before touching result.value or result.reason.

One loop does the cycling here: for (const result of settled). Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Using it

The main signature reads const load = (id: string)

The output keeps result order — ok: 21, failed: station offline, ok: 21 — with the failed line reached through the unknown-typed reason narrowed by instanceof Error.

Running the file executes main, which drives load in order.

Key statements

const settled = await Promise.allSettled([load('a'), load('bad'), load('c')]);
id === 'bad' ? Promise.reject(new Error('station offline')) : Promise.resolve({ celsius: 21 });

FAQ

What does Promise.allSettled Narrows Settled Results print when run?
Running the file directly is enough — expect labeled output lines such as `ok:`, `failed:`.