【发布时间】:2023-03-16 21:05:01
【问题描述】:
我正在学习 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');
});
}
我如何知道所有异步请求何时完成?
【问题讨论】:
-
Promise.all是你需要了解的内容 -
@JaromandaX 感谢您的回复...
-
有时授人以鱼不如授人以渔
-
@JaromandaX 确实如此.. erm 我可以从下面的答案中问回问题吗?这是处理异步请求的最佳方法吗?还是这只是复杂的?
标签: javascript node.js api request promise