#Promises#Async

Resolve Promises Sequentially

Run promises one after another and collect the results in order — built with .then chaining, no async/await.

By Pratik RaiMedium

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

Input:

JSfile.javascript
1const 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.

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(...).

Goal: Resolve every promise in order using .then chaining, and return the values as an array.

Source

Frequently asked questions

What is the difference between sequential and parallel promises?
Parallel starts every promise immediately and waits for them all, so the total is the slowest one. Sequential starts each only after the previous resolves, so the total is the sum. The difference is decided by *when you call* the functions, not by where you await.
How do you run promises sequentially without async/await?
Keep one chain variable starting at `Promise.resolve()` and reassign it each iteration with `chain = chain.then(() => next())`. The loop builds the chain; each link creates its promise only when reached.
Why would an interviewer ban async/await here?
Because the `async` version hides the mechanism. Written as a fold over `.then`, it is obvious that the next promise is created inside the previous callback, which is the entire reason it runs sequentially.
When is sequential actually the right choice?
When each call depends on the previous result, when you must not overwhelm a rate-limited API, or when order of side effects matters. Otherwise parallel is faster and usually correct.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

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 · ES6Pratik Rai ·

JavaScript

Promise Time Limit

Wrap an async function so it gives up after a deadline — the building block behind every request timeout.

JavaScript · ES6Pratik Rai ·

JavaScript

Promisify a Callback Function

Convert a Node-style (error, value) callback API into one that returns a promise.

JavaScript · ES6Pratik Rai ·