Promise.race Settles On The First Outcome

Promise.race settles as soon as the first promise settles, win or lose, so timeouts and hedged reads come from one combinator while losing tasks keep running.

JavascriptResilience

Code

javascriptsnippet
24 lines
// Promise.race:第一个敲定(兑现或拒绝)的 promise 决定整体结果
function sleep(ms, value) {
  return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}

const sources = [
  sleep(120, 'cache'),
  sleep(60, 'disk'),
  sleep(200, 'network'),
];
const winner = await Promise.race(sources);
console.log('winner:', winner);

// race 不取消落败者:它们继续跑完,只是结果被丢弃
const straggler = sleep(200, 'late but done');
straggler.then((value) => console.log('still finished:', value));

// 拒绝也算敲定:最先失败的结果原样抛出,用 try/catch 接住
const boom = new Promise((_, reject) => setTimeout(() => reject(new Error('boom')), 30));
try {
  await Promise.race([sleep(300, 'ok'), boom]);
} catch (err) {
  console.log('caught:', err.message);
}

Output

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

winner: disk
caught: boom
still finished: late but done

How it works

The snippet is organized around the function sleep.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

It builds and returns a fresh value rather than reusing its inputs.

Applying it

The main signature reads function sleep(ms, value)

The demo output is labeled (winner:, still finished:, caught:), so every printed line maps back to its originating operation.

Statements that matter

return new Promise((resolve) => setTimeout(() => resolve(value), ms));
const boom = new Promise((_, reject) => setTimeout(() => reject(new Error('boom')), 30));
await Promise.race([sleep(300, 'ok'), boom]);

Interactive Tools for This Topic

FAQ

Does `sleep` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `sleep` at load time.