javascript - 如何循环请求 promise API 请求调用?

标签 javascript node.js api request promise

我正在学习 Node.JS,我被介绍到 request-promise 包。我将它用于 API 调用,但遇到无法对其应用循环的问题。

这是显示简单 API 调用的示例:

var read_match_id = {
    uri: 'https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/V001',
    qs: {
        match_id: "123",
        key: 'XXXXXXXX'
    },
    json: true
};

rp(read_match_id)
.then(function (htmlString) {
    // Process html...
})
.catch(function (err) {
    // Crawling failed...
});

我怎样才能有这样的循环:

 var match_details[];
 for (i = 0; i < 5; i++) {
     var read_match_details = {
              uri: 'https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001',
            qs: {
                  key: 'XXXXXXXXX',
                  match_id: match_id[i]
                },
            json: true // Automatically parses the JSON string in the response 
    };
    rp(read_match_details)
       .then (function(read_match){
            match_details.push(read_match)//push every result to the array
        }).catch(function(err) {
            console.log('error');
        });
    }

我怎么知道所有异步请求何时完成?

最佳答案

request-promise 使用 Bluebird for Promise。

简单的解决方案是 Promise.all(ps),其中 ps 是 promise 数组。

var ps = [];
for (var i = 0; i < 5; i++) {
    var read_match_details = {
        uri: 'https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001',
        qs: {
            key: 'XXXXXXXXX',
            match_id: match_id[i]
        },
        json: true // Automatically parses the JSON string in the response 
    };
    ps.push(rp(read_match_details));
}

Promise.all(ps)
    .then((results) => {
        console.log(results); // Result of all resolve as an array
    }).catch(err => console.log(err));  // First rejected promise

唯一的缺点是,在任何 promise 被拒绝后,这将立即进入 catch block 。 4/5 已解决,没关系,1 被拒绝将全力以赴。

替代方法是使用 Bluebird 的检查 ( refer this )。我们会将所有 promise 映射到它们的反射,我们可以对每个 promise 进行 if/else 分析,并且即使任何 promise 被拒绝它也会起作用

// After loop
ps = ps.map((promise) => promise.reflect()); 

Promise.all(ps)
    .each(pInspection => {
        if (pInspection.isFulfilled()) {
            match_details.push(pInspection.value())
        } else {
            console.log(pInspection.reason());
        }
    })
    .then(() => callback(match_details)); // Or however you want to proceed

希望这能解决您的问题。

关于javascript - 如何循环请求 promise API 请求调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39506858/

相关文章:

java - 如何通过类 org.apache.hadoop.conf.Configuration 在 java 客户端中设置 hadoop 复制?

rest - 设计Restful API时,UNFOLLOW应该用DELETE还是POST?

javascript - 推送多个 json 数组 - javascript

持有 jquery 对象的 javascript 对象?

javascript - 嵌套函数调用nodejs

node.js - intel XDK目录浏览

api - Grails-向API发送 “multipart/form-data”请求

javascript - 从 jquery 方法中提取变量

PHP 与 JavaScript 正则表达式

javascript - 如何在 Pug 中渲染详细 View 而不是其所有对象?