Resolve Promises Sequentially

PromisesAsyncInterview Question

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.

Examples

Example 1
Input
const get = (i) => (i < 3
  ? new Promise((r) => setTimeout(() => r(i * 10), 100))
  : null);

await promiseAllSync(get, 3);
Output
[0, 10, 20]  // after ~300ms
Explanation
Sequential, so the three 100ms waits add up. Promise.all would have taken 100ms and defeated the point.

Constraints

  • 0 <= count <= 10
  • A rejection anywhere rejects the whole result

Notes

  • Reassigning one `chain` variable inside a loop is the idiom: `chain = chain.then(...)`.

Hints

Read the full write-up for Resolve Promises Sequentially
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it