繁体   English   中英

如何循环请求承诺API请求调用?

[英]How to loop request-promise API request call?

我正在学习Node.JS,并向我介绍了请求承诺包。 我将其用于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进行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

这样做的唯一缺点是,在任何应许被拒绝后,这将立即导致阻塞。 4/5解决,没关系,1个被拒绝将全力以赴。

另一种方法是使用Bluebird的检查( 请参阅参考资料)。 我们将所有承诺映射到它们的反映,我们可以对每个承诺进行if / else分析, 即使任何一个承诺被拒绝它也将起作用

// 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

希望这能解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM