Promise Pool With a Concurrency Limit
Run a list of async tasks with a hard limit on how many are in flight at once — the concurrency control Promise.all does not give you.
JavaScript · ES6 — Pratik Rai ·
Give the caller a way to stop waiting on a promise — the pattern behind cancelling a request when a component unmounts.
Write cancellable(promise) returning { promise, cancel }.
The returned promise settles exactly as the original does, except that calling cancel() before it settles rejects it with the string "Cancelled". Calling cancel() afterwards must do nothing.
Input:
JSfile.javascript1const { promise, cancel } = cancellable( 2 new Promise((r) => setTimeout(() => r('done'), 500)) 3); 4cancel(); 5promise.catch(console.log);
Output:
"Cancelled"
cancel() ran before the 500ms timer, so the result never arrives.
AbortController is what actually aborts a fetch.A promise has no cancel. Once created it will settle, and the only question is whether anyone is still listening. Cancellation is therefore about the listener, not the work.
Make a second promise whose reject you keep, and race it against the original.
JSfile.javascript1function cancellable(promise) { 2 let cancel; 3 const gate = new Promise((_, reject) => { cancel = () => reject('Cancelled'); }); 4 gate.catch(() => {}); 5 return { promise: Promise.race([promise, gate]), cancel }; 6}
You need no "has it settled" flag: a promise settles once, so a cancel() after the fact is a no-op for free.
Be honest about what this does. The underlying work carries on — the timer still fires, the request still completes and its response is still downloaded. AbortController passed to fetch genuinely aborts the request, and is what you would use in a component that unmounts mid-flight.
Goal: Reject with "Cancelled" when cancel comes first, and behave like the original otherwise.
AbortController passed to fetch genuinely aborts the request, so the browser stops downloading and the server sees a dropped connection.Continue learning with these related challenges
Run a list of async tasks with a hard limit on how many are in flight at once — the concurrency control Promise.all does not give you.
JavaScript · ES6 — Pratik Rai ·
Wrap an async function so it gives up after a deadline — the building block behind every request timeout.
JavaScript · ES6 — Pratik Rai ·
Convert a Node-style (error, value) callback API into one that returns a promise.
JavaScript · ES6 — Pratik Rai ·
Run a list of async tasks with a hard limit on how many are in flight at once — the concurrency control Promise.all does not give you.
JavaScript · ES6
Pratik Rai ·
Wrap an async function so it gives up after a deadline — the building block behind every request timeout.
JavaScript · ES6
Pratik Rai ·
Convert a Node-style (error, value) callback API into one that returns a promise.
JavaScript · ES6
Pratik Rai ·