我正在学习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');
});
}我如何知道所有异步请求何时都已完成?
发布于 2016-09-15 17:41:29
request-promise使用Bluebird作为Promise。
简单的解决方案是Promise.all(ps),其中ps是promises数组。
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分析,即使任何一个承诺被拒绝了,它也会起作用。。
// 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希望这能解决你的问题。
https://stackoverflow.com/questions/39506858
复制相似问题