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

不想你离开。 提交于 2019-12-19 09:24:04

问题


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?


回答1:


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.




回答2:


Bluebird supports multiple concurrent Promises.

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

There are two ways to do it:

.all() - good for a dynamic number of promises

.join() - good for a fixed number of promises and as for Bluebird's documentation, it supplies a better performance than .all() method.

From bluebird's documentation:

 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);
});



回答3:


Found the solution.

Use .settle




回答4:


I use q Promise Maybe help

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

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



来源:https://stackoverflow.com/questions/28164642/how-to-do-parallel-async-multiple-requests-at-once-with-promises-in-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!