LearnFrenzy
Sign in Take a free test

Promises · Promises Coding Problems · Question 4

Run promise tasks in sequence in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Given an array of functions that return promises, run them one after another (each starting only when the previous finished) using reduce, collecting all results.

Solution
main.js
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const migration = (name, ms) => () => sleep(ms).then(() => { console.log("applied", name); return name; });

const migrations = [migration("001_users", 20), migration("002_orders", 5), migration("003_indexes", 10)];

migrations
  .reduce((chain, run) => chain.then((done) => run().then((name) => [...done, name])), Promise.resolve([]))
  .then((all) => console.log(`${all.length} migrations applied in order`));

Output Verified by running it on Node.js

applied 001_users
applied 002_orders
applied 003_indexes
3 migrations applied in order

The array holds functions, not promises, so nothing starts early. Each reduce step chains the next migration onto the previous promise – order is guaranteed even though the first one is slowest.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links