How to execute parallel asynchronous multiple requests simultaneously with Promises in Node

Array and loop, but I want to be able to run all of them in parallel, because I do not want to run one after the other.

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

I use Bluebird, how can I use its functions to solve this problem?

+2
source share
4 answers

You can use Promise.mapwith .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; })
    });
}

, , http .

+4

Bluebird Promises.

. : https://github.com/petkaantonov/bluebird/blob/master/API.md#promisejoinpromisethenablevalue-promises-function-handler---promise

:

. all() - promises

. join() - promises, Bluebird , .all().

bluebird:

 var Promise = require("bluebird");
 var join = Promise.join;

join(getPictures(), getComments(), getTweets(),
function(pictures, comments, tweets) {
console.log("in total: " + pictures.length + comments.length + tweets.length);
});
+4

I am using q Promise Help is possible

return q.all([function or value1, function or value 2, ......])
.spread(function (result1, result2, ....) {
   // do somethine
})

............

-1
source

Source: https://habr.com/ru/post/1606287/


All Articles