如何使用Node中的Promises一次并行执行多个异步请求 [英] How to do parallel async multiple requests at once with Promises in Node

查看:97
本文介绍了如何使用Node中的Promises一次并行执行多个异步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数组并循环通过,但我希望能够并行运行所有它们,因为我不想一个接一个地运行.

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.

我正在使用Bluebird,如何使用其功能来解决此问题?

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

推荐答案

您可以将Promise.map.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代理可能会限制请求.

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

这篇关于如何使用Node中的Promises一次并行执行多个异步请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆