Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to run a given array of promises in series in JavaScript?
In JavaScript, there is a method called "Promise.all" that allows you to run an array of promises in parallel. However, sometimes you may want to run your promises in series instead. This can be useful if you want to make sure that each promise is executed one after the other, or if you need to use the result of one promise in the execution of the next promise.
There are a few different ways that you can run an array of promises in series in JavaScript. In this article, we'll take a look at a few of them.
Using Promise.prototype.then()
One way to run an array of promises in series is to chain them together using the then() method. This method takes a function as its input, which will be executed after the promise is fulfilled.
Example
<html>
<head>
<title>Examples</title>
</head>
<body>
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
<script>
Promise.resolve(1)
.then(result => {
document.getElementById("result1").innerHTML = result;
return Promise.resolve(2);
})
.then(result => {
document.getElementById("result2").innerHTML = result;
return Promise.resolve(3);
})
.then(result => {
document.getElementById("result3").innerHTML = result;
});
</script>
</body>
</html>
1 2 3
As you can see, we're using the then() method to chain together three promises. The first promise resolves to the value 1, which is displayed. The second promise resolves to the value 2, which is also displayed. And finally, the third promise resolves to the value 3, which is displayed.
Because the "then" method returns a promise, we can chain promises together in this way to create a series.
Using for-await-of Loop
Another way to run an array of promises in series is to use the "for-await-of" loop. This loop allows you to use the await keyword inside of a for loop. The await keyword pauses the execution of the code until the promise is fulfilled.
Example
<html>
<head>
<title>Example- for-await-of</title>
</head>
<body>
<script>
async function runPromisesInSeries() {
for await (const promise of [
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3),
]) {
const result = await promise;
document.write(result);
document.write("<br>");
}
}
runPromisesInSeries();
</script>
</body>
</html>
1 2 3
In this example, we have an async function that contains a "for-await-of" loop. This loop iterates over an array of promises. For each promise in the array, we await the promise to be fulfilled. Once the promise is fulfilled, the value is displayed.
Using Array.reduce() Method
A more flexible approach is using Array.reduce() to sequentially execute promises. This method allows you to accumulate results while maintaining sequential execution.
Example
<html>
<head>
<title>Sequential Promises with reduce</title>
</head>
<body>
<div id="output"></div>
<script>
const promiseArray = [
() => Promise.resolve(1),
() => Promise.resolve(2),
() => Promise.resolve(3)
];
promiseArray.reduce((prevPromise, currentPromise) => {
return prevPromise.then((result) => {
if (result) {
document.getElementById("output").innerHTML += result + "<br>";
}
return currentPromise();
});
}, Promise.resolve()).then((finalResult) => {
document.getElementById("output").innerHTML += finalResult;
});
</script>
</body>
</html>
1 2 3
Using External Libraries
If you need more functionality than what's provided by the native Promise API, you can use a library like Bluebird or Q. These libraries provide additional methods for working with promises.
For example, Bluebird provides a "mapSeries" method that processes array elements sequentially:
const Promise = require('bluebird');
Promise.mapSeries([1, 2, 3], x => {
return Promise.resolve(x * 2);
}).then(results => {
console.log(results); // [2, 4, 6]
});
Comparison of Methods
| Method | Complexity | Flexibility | Browser Support |
|---|---|---|---|
| Promise.then() chaining | Medium | Limited | Excellent |
| for-await-of | Low | High | Modern browsers |
| Array.reduce() | Medium | Very High | Excellent |
| External Libraries | Low | Very High | Depends on library |
Conclusion
Running promises in series ensures sequential execution, which is crucial when promises depend on each other's results. The for-await-of loop provides the cleanest syntax for modern JavaScript, while Array.reduce() offers maximum flexibility for complex scenarios.
