Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do parallel async multiple requests at once with Promises in Node

Array and loops through but I want to be able to run all of them in parallel instead as I don't want to run one after another.

I basically want to store all endpoint calls status codes, body and time as array and return them as results regardless of there are errors or not in the endpoint.

I'm using Bluebird, how can I use its features to solve this issue?

like image 281
Passionate Engineer Avatar asked Jan 09 '23 00:01

Passionate Engineer


1 Answers

You can use Promise.map with .bind:

function getComponentStatuses(componentsToCheck) {
    return Promise.map(componentsToCheck, function() {
        var start = Date.now();
        return getAsync({
            url: component.endpoint,
            timeout: component.timeout
        })
        .bind({
             name: component.name,
             status: null,
             body: null,
             time: null
        })
        .spread(function(response, body){
            Logger.info('GET took ' + end + 'ms.');
            this.status = response.statusCode;
            this.body = body;
            return this;
        })
        .catch(function(e) { return this; })
        .finally(function() { this.time = Date.now() - start; })
    });
}

Note that your timing method is incorrect because the http agent might throttle requests.

like image 89
Esailija Avatar answered Jan 21 '23 14:01

Esailija