Working with Multiple Promises: Gathering All Promises
Let's discuss the second approach, the all() method, to deal with the multiple promises.
We'll cover the following...
“The
all()
static method of promise takes an array of promises and passes an array of resolved results to thethen()
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.
Press + to interact
'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:LAUNCHif(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()
: TheisPrime()
function returns aboolean