Promise.withResolvers Exposes Resolve And Reject
Settle a promise from outside its executor with Promise.withResolvers: hand resolve or reject to any callback, then await the promise like any other.
Code
// Promise.withResolvers(ES2024):把 promise 与它的 resolve/reject
// 一起交出来,执行器之外的普通回调也能事后决定结果。
const settled = Promise.withResolvers();
setTimeout(() => settled.resolve('loaded'), 10);
const first = await settled.promise;
console.log('settled with:', first);
// 拒绝路径一样:reject 之后消费者按普通 rejection 处理
const attempt = Promise.withResolvers();
attempt.reject(new Error('disk full'));
try {
await attempt.promise;
} catch (err) {
console.log('caught:', err.message);
}
// 典型场景:把多个信号源桥接成一个一次性 promise,谁先到谁结算
function firstSignal(signals) {
const gate = Promise.withResolvers();
for (const { text, delay } of signals) {
setTimeout(() => gate.resolve(text), delay);
}
return gate.promise;
}
const winner = await firstSignal([{ text: 'watchdog', delay: 60 }, { text: 'worker', delay: 15 }]);
console.log('first signal:', winner);Output
Captured from a sandboxed run of this snippet in the build pipeline.
settled with: loaded
caught: disk full
first signal: workerHow it works
The snippet is organized around the function firstSignal.
Repetition is confined to for (const { text, delay } of signals) — the rest of the file is straight-line. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Putting it to use
The main signature reads function firstSignal(signals)
The demo output is labeled (settled with:, caught:, first signal:), so every printed line maps back to its originating operation.
Core lines
const winner = await firstSignal([{ text: 'watchdog', delay: 60 }, { text: 'worker', delay: 15 }]);
setTimeout(() => settled.resolve('loaded'), 10);
setTimeout(() => gate.resolve(text), delay);
Interactive Tools for This Topic
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `firstSignal` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.