且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Node中的Promises一次并行执行多个异步请求

更新时间:2022-01-12 04:51:02

您可以将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.