typescript / expert
Snippet
Externally-Controlled Promises via Promise.withResolvers
Promise.withResolvers (ES2024, TS 5.4+) returns the promise together with its resolve and reject functions without forcing you to capture them inside the executor callback. This avoids the awkward 'let resolve!; new Promise(r => { resolve = r; })' deferred-pattern and lets you build cancellation tokens, semaphores, or event-driven gates that resolve from outside the constructor scope. The strongly typed generic parameter keeps the resolved value's shape intact, and wrapping it in a helper like createGate adds idempotence — a critical property when multiple callers might race to settle the same future.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function createGate<T>() {const { promise, resolve, reject } = Promise.withResolvers<T>();let settled = false;return {promise,open(value: T) {if (settled) return;settled = true;resolve(value);},fail(err: unknown) {if (settled) return;settled = true;reject(err);},};}const gate = createGate<number>();setTimeout(() => gate.open(42), 100);const value = await gate.promise; // 42
Breakdown
1
const { promise, resolve, reject } = Promise.withResolvers<T>();
Destructures the trio in one call — no more deferred-pattern boilerplate.
2
let settled = false;
Local flag enforces idempotence so a second open/fail call is a no-op.
3
open(value: T) { if (settled) return; settled = true; resolve(value); }
Externally settles the promise exactly once, even under concurrent callers.
4
const value = await gate.promise;
Consumer side awaits as usual; nothing changes for the caller.