Promise.withResolvers Builds A Start Gate
Create externally settled promises with Promise.withResolvers and share one as a start gate that several async workers await before the main flow releases them.
Code
// Promise.withResolvers: 把 resolve / reject 交到函数外部手上
interface Job {
id: number;
}
function createStartGate(): { signal: Promise<void>; begin: () => void } {
const { promise, resolve } = Promise.withResolvers<void>();
return { signal: promise, begin: resolve }; // 重命名后交给外部
}
const { signal, begin } = createStartGate();
async function worker(job: Job): Promise<string> {
await signal; // 每个 worker 都在栅栏前停住
return `job ${job.id} ran`;
}
const jobs: Job[] = [{ id: 1 }, { id: 2 }, { id: 3 }];
// 先挂起所有 worker,前置准备完成后再统一放行
const running = jobs.map((job) => worker(job));
begin();
const settled = await Promise.all(running);
console.log(settled.join(', '));Output
Captured from a sandboxed run of this snippet in the build pipeline.
job 1 ran, job 2 ran, job 3 ranWhat the code does
Promise.withResolvers Builds A Start Gate is built around the functions createStartGate and worker.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
The result comes back as an object carrying promise.
Applying it
The main signature reads function createStartGate()
The call returns promise.
Statements that matter
function createStartGate(): { signal: Promise<void>; begin: () => void } {
const { promise, resolve } = Promise.withResolvers<void>();
return { signal: promise, begin: resolve }; // 重命名后交给外部
}
const settled = await Promise.all(running);
async function worker(job: Job): Promise<string> {
await signal; // 每个 worker 都在栅栏前停住
return `job ${job.id} ran`;
}
Interactive Tools for This Topic
FAQ
- Does `createStartGate` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `createStartGate`, `worker` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.