首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何循环request-promise API请求调用?

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

Stack Overflow用户
提问于 2016-09-15 16:54:42
回答 1查看 12.1K关注 0票数 3

我正在学习Node.JS,并且我被介绍到了request-promise包。我使用它来进行API调用,但是我遇到了一个问题,我不能对它应用循环。

下面的示例展示了一个简单的API调用:

代码语言:javascript
复制
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...
});

我怎么能有这样的循环:

代码语言:javascript
复制
 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');
        });
    }

我如何知道所有异步请求何时都已完成?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-15 17:41:29

request-promise使用Bluebird作为Promise。

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

代码语言:javascript
复制
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

这样做的唯一缺点是,在任何承诺被拒绝后,这将立即转到catch block。4/5已解决,无关紧要,1个被拒绝将抛出所有内容来捕获。

另一种方法是使用蓝鸟的检查(refer this)。我们将所有的承诺映射到它们的反射,我们可以为每个承诺做一个if/else分析,即使任何一个承诺被拒绝了,它也会起作用。。

代码语言:javascript
复制
// 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

希望这能解决你的问题。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39506858

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档