Async & Promisesmedium
Execute an array of async tasks in sequence
Given an array of async functions (each returning a Promise), execute them one after another — not concurrently — and collect the results.
Asked at Apple, Amazon, Stripe
Answer
// Using Array.reduce function runSequential(tasks) { return tasks.reduce( (chain, task) => chain.then(results => task().then(value => [...results, value]) ), Promise.resolve([]) ) } // Using async/await (often cleaner in interviews) async function runSequential(tasks) { const results = [] for (const task of tasks) { results.push(await task()) } return results } // Test const tasks = [ () => Promise.resolve(1), () => new Promise(res => setTimeout(() => res(2), 100)), () => Promise.resolve(3), ] runSequential(tasks).then(console.log) // [1, 2, 3]