A Promise Settles Once; Later Calls No-Op
A promise locks its state on the first resolve or reject; every later settle call is a no-op, while extra then observers still see the settled value.
Code
// executor 里只有第一次 settle 生效:后续 resolve/reject 全部被忽略
const p = new Promise((resolve, reject) => {
resolve('first');
resolve('second');
reject(new Error('too late'));
});
p.then((value) => console.log('settled with:', value));
// 同一状态可挂多个观察者,各自都拿到定型的结果
p.then((value) => console.log('observer 2:', value));
// race 共享同一语义:先到先得
const slow = new Promise((resolve) => setTimeout(() => resolve('slow'), 30));
const fast = new Promise((resolve) => setTimeout(() => resolve('fast'), 5));
Promise.race([slow, fast]).then((winner) => console.log('race winner:', winner));
// reject 生效后 resolve 也是 no-op;状态不会反转
const flipped = new Promise((resolve, reject) => reject(new Error('early')));
flipped.catch((err) => console.log('caught:', err.message));Output
Captured from a sandboxed run of this snippet in the build pipeline.
settled with: first
observer 2: first
caught: early
race winner: fastWhat the code does
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Each step operates on the top-level bindings: slow, fast, flipped.
Applying it
The demo output is labeled (settled with:, observer 2:, race winner:), so every line of output can be traced to the operation that made it.
Statements that matter
const slow = new Promise((resolve) => setTimeout(() => resolve('slow'), 30));
const flipped = new Promise((resolve, reject) => reject(new Error('early')));
const fast = new Promise((resolve) => setTimeout(() => resolve('fast'), 5));
Interactive Tools for This Topic
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Its state lives in module-level bindings: `slow`, `fast`, `flipped`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.