Introduction
In this lab, we will be exploring how to run an array of promises in series using JavaScript. We will be using the Array.prototype.reduce() method to create a promise chain, where each promise returns the next promise when resolved. By the end of this lab, you will have a better understanding of how to execute promises sequentially, taking your programming skills to the next level.
Running Promises in a Series
To execute an array of promises in a series, use Array.prototype.reduce() to create a promise chain. Each promise returns the next promise after being resolved.
To start, open the Terminal/SSH and type node to begin practicing coding.
Here's an example of the code:
const runPromisesInSeries = (ps) =>
ps.reduce((p, next) => p.then(next), Promise.resolve());
You can then use the runPromisesInSeries function to execute promises sequentially, as shown in the following example:
const delay = (d) => new Promise((r) => setTimeout(r, d));
runPromisesInSeries([() => delay(1000), () => delay(2000)]);
// This code runs each promise sequentially, taking a total of 3 seconds to complete.
Summary
Congratulations! You have completed the Run Promises in Series lab. You can practice more labs in LabEx to improve your skills.