Search⌘ K
AI Features

Working with Multiple Promises: Gathering All Promises

Explore how to manage multiple promises concurrently with the Promise.all method in JavaScript. Understand its behavior when resolving or rejecting promises, and see practical implementations such as processing files asynchronously. Learn to handle errors effectively when any asynchronous task fails, and discover strategies to prevent long-running operations from causing delays.

“The all() static method of promise takes an array of promises and passes an array of resolved results to the then() function when all promises resolve.”

If any one of the given promises is rejected, the then() function is not called. The catch() function is used instead.

Service

We will soon use the all() function to work with multiple asynchronous tasks. However, before we get to the all() function, we need to create a small program that will execute calls concurrently. This will help you see the power of the all() method when ran asynchronously and concurrently.

Node.js
'use strict';
const cluster = require('cluster');
const http = require('http');
const url = require('url');
const querystring = require('querystring');
const port = 8084;
const number_of_processes = 1;
const isPrime = function(number) {
for(let i = 2; i < number; i++) {
if (number % i === 0) {
return false;
}
}
return number > 1;
};
const countNumberOfPrimes = function(number) {
let count = 0;
for(let i = 1; i <= number; i++) {
if(isPrime(i)) {
count++;
}
}
return count;
};
const handler = function(request, response) {
const params = querystring.parse(url.parse(request.url).query);
const number = parseInt(params.number);
const count = countNumberOfPrimes(number);
response.writeHead(200, { 'Content-Type': 'text/plain' });
return response.end(`${count}`);
};
//START:LAUNCH
if(cluster.isMaster) {
for(let i = 0; i < number_of_processes; i++) {
cluster.fork();
}
} else {
http.createServer(handler).listen(port);
}
//END:LAUNCH

Code explanation

This example shows a small HTTP server that runs in node.js.

  • isPrime(): The isPrime() function returns a boolean
...