如何循环请求-承诺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
为承诺数组。
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块。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
相关文章:
- 如何判断请求/承诺是否需要超过5秒才能完成,angular js
- EmberJS:在成功处理请求时解决承诺
- 你如何正确地承诺请求
- jQuery ajax 请求与承诺在IE9中不起作用
- 如何在 ajax 请求中使用承诺对强制数据
- 有问题与承诺角度.控制台日志不适用于 HTTP 请求
- 如何在节点中使用承诺一次并行异步多个请求
- 节点.JS - 如何限制多承诺的请求以防止溢出(Web 抓取)
- 使用请求-承诺的嵌套异步请求
- Koa.js承诺的请求悬而未决
- 为延迟请求处理创建承诺链
- 承诺解析错过异步请求循环的一个值
- Javascript 多个承诺不适用于 q 和请求中间
- 流星:返回承诺's,然后再响应HTTP发布请求
- 用请求承诺替换节点request.post
- 是否存在“脱屏”的设计模式?许多请求'same'的承诺
- 承诺的请求在解析时没有返回正确的结果
- 使用请求承诺在Electron中链接HTTP请求
- 如何循环请求-承诺API请求调用
- 如何正确处理请求-承诺错误