Promise Pool
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 ·
Run promises one after another and collect the results in order — built with .then chaining, no async/await.
getPromiseByIndex(i) returns the promise for index i, or null when there are none left.
Write promiseAllSync(getPromiseByIndex, count) that resolves each one in order — the next must not start until the previous has resolved — and resolves with an array of the values.
Build the chain with .then(). The interviewer asked for it without async/await on purpose.
Input:
JSfile.javascript1const get = (i) => (i < 3 2 ? new Promise((r) => setTimeout(() => r(i * 10), 100)) 3 : null); 4 5await promiseAllSync(get, 3);
Output:
[0, 10, 20] // after ~300ms
Sequential, so the three 100ms waits add up. Promise.all would have taken 100ms and defeated the point.
chain variable inside a loop is the idiom: chain = chain.then(...).Goal: Resolve every promise in order using .then chaining, and return the values as an array.
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 ·