Execute promises in sequence

node v18.11.0
version: 1.0.0
endpointsharetweet
function executePromisesInSequence(tasks) { return tasks.reduce((promiseChain, currentTask) => { return promiseChain.then(currentTask); }, Promise.resolve()); // Start with a resolved promise } // Example usage: const task1 = () => new Promise(resolve => { setTimeout(() => { console.log("Task 1 completed"); resolve(1); }, 1000); }); const task2 = () => new Promise(resolve => { setTimeout(() => { console.log("Task 2 completed"); resolve(2); }, 500); }); const task3 = () => new Promise(resolve => { setTimeout(() => { console.log("Task 3 completed"); resolve(3); }, 700); }); // Array of promise-returning functions const tasks = [task1, task2, task3]; executePromisesInSequence(tasks).then(() => { console.log("All tasks completed in sequence"); });
Loading…

no comments

    sign in to comment