Create a pending promise, then settle it from a button click or a timeout โ
completely outside the code that created it. That's the whole point of
Promise.withResolvers(): resolve and reject live in your
scope, ready for later.
The promise below is created once, up front. Confirm, Cancel, and the timeout all fire later, from outside โ exactly like a real "are you sure?" dialog or a socket event.
resolve and reject are ordinary functions sitting in this scope โ
call either one from anywhere, anytime. Once the promise settles, every later call is
silently ignored: the first settlement always wins. Try the last preset,
or click Confirm and then Cancel yourself, to see it happen.
let resolve, reject; const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
const { promise, resolve, reject } = Promise.withResolvers();
Both give you the same three things โ a promise plus its resolve/reject functions, free to hand to code outside the constructor. The right side just skips the manual "declare outer variables, then capture them" dance. This demo's buttons call the right-hand form (or the polyfill below, if your browser lacks it).