Explain Codes LogoExplain Codes Logo

Resolve promises one after another (i.e. in sequence)?

javascript
async-await
promise-engineering
best-practices
Nikita BarsukovbyNikita Barsukov·Mar 5, 2025
TLDR

Chain promises sequentially using .reduce() with Promise.resolve() as the initial value. Let's unveil the secret sauce for this:

let promiseFunctions = [func1, func2, func3]; // functions that return promises, not Christmas presents! promiseFunctions.reduce((chain, promiseFunction) => chain.then(promiseFunction), Promise.resolve());

Replace func1, func2, func3 with your promise-returning functions. Follow this and watch each promise bow to the previous one before executing, keeping the sequence intact. It's like a disciplined line outside a Star Wars premier!

Upgrade with async/await

The good ol' reduce() is slick. However, occasionally you'd want the clarity of async/await like a clear sky for stargazing. Here's how:

const runSequentially = async (promiseFunctions) => { let results = []; // Here’s where we’ll stash the loot for (let promiseFunction of promiseFunctions) { results.push(await promiseFunction()); // Wait for each gold nugget to be dug up, then add it to our stash } return results; // And voila! Sequential execution and sanity! };

Collect all the Easter eggs

If hunting for results from each promise is your thing, modify .reduce() to gather them eggs:

promiseFunctions.reduce((chain, promiseFunction) => { return chain.then((resultArray) => promiseFunction().then(result => resultArray.concat(result)) // Gathering the results like infinity stones ); }, Promise.resolve([]));

Get a shiny array of resolved values in perfect pecking order.

Big League promises with Bluebird

Third-party libraries like Bluebird is like the knight in the shining armor, riding in with Promise.each() to ensure orderly execution:

Promise.each(promiseFunctions, function(promiseFunction) { return promiseFunction(); // one after another, like a disciplined Bermuda convoy });

Judge your project requirements and standards before tying the knots with external dependencies.

Your safety belt – Best practices & precautions

For a bump-free ride on the promise highway, buckle up with these guidelines:

Avoid recursion pitfalls

Steer clear of stack overflow errors by swapping recursive functions with reduce() or async/await. Basically, don't tie your shoe laces together.

Ensure compatibility

Be a wise owl and verify environment support for latest syntax such as async/await and async generators. For backward compatibility, trust your transformation tools.

Keep it clean and modular

Break those lengthy chains into manageable bits to clear the fog. It's like a lego set - easy to construct, deconstruct and comprehend.

Use modern syntax for clarity

Did someone say readability? ES6 features like arrow functions are your lifesavers. Because who wouldn't appreciate shorter, cleaner code?