我正在使用Node.js中的axios和promises通过他们的web API调用Steam的一个游戏的api端点。来自端点的每个JSON响应都会返回100个匹配对象,其中只有大约10到40个(平均)与我的用例相关。此外,我观察到,如果在比方说一秒钟内多次调用,数据往往会重复。我试图实现的是通过连续(递归地)调用match_id
,直到获得100个满足我的目的的唯一match_id
,从而在一个数组中获得符合我的条件的100个api (而不是整个匹配对象)。
我知道在循环内调用端点是幼稚的,它超出了他们的web api设置的每秒1个请求的调用限制。这就是为什么我求助于递归来确保每个promise都被解析,并且在继续之前用match_id
填充数组。我遇到的问题是,我的代码没有终止,并且在递归调用的每个阶段,值都是相同的(例如,最后一个匹配id,实际构建的数组,等等)。
function makeRequestV2(matchesArray, lastId) {
// base case
if (matchesArray.length >= BATCH_SIZE) {
console.log(matchesArray);
return;
}
steamapi
.getRawMatches(lastId)
.then(response => {
const matches = response.data.result.matches;
// get the last id of fetched chunk (before filter)
const lastIdFetched = matches[matches.length - 1].match_id;
console.log(`The last Id fetched: ${lastIdFetched}`);
let filteredMatches = matches
.filter(m => m.lobby_type === 7)
.map(x => x.match_id);
// removing potential dups
matchesArray = [...new Set([...matchesArray, ...filteredMatches])];
// recursive api call
makeRequestV2(matchesArray, lastIdFetched);
})
.catch(error => {
console.log(
"HTTP " + error.response.status + ": " + error.response.statusText
);
});
}
makeRequestV2(_matchIds);
// this function lies in a different file where the axios call happens
module.exports = {
getRawMatches: function(matchIdBefore) {
console.log("getRawMatches() executing.");
let getURL = `${url}${config.ENDPOINTS.GetMatchHistory}/v1`;
let parameters = {
params: {
key: `${config.API_KEY}`,
min_players: `${initialConfig.min_players}`,
skill: `${initialConfig.skill}`
}
};
if (matchIdBefore) {
parameters.start_at_match_id = `${matchIdBefore}`;
}
console.log(`GET: ${getURL}`);
return axios.get(getURL, parameters);
}
}
我没有超过请求限制和所有这些,但相同的结果不断出现。
BATCH_SIZE
是100
和_matchIds = []
发布于 2019-08-11 13:42:50
我将从替换这一行开始:
matchesArray = [...new Set([...matchesArray, ...filteredMatches])];
使用这一条:
filteredMatches.filter(item => matchesArray.indexOf(item) === -1).forEach(item=>{ matchesArray.push(item) })
您所做的是将函数中的matchesArray变量有效地替换为新引用。我的意思是,你在函数参数中从外部发送的变量不再是函数内部的变量。如果您使用matchesArray.push -您不会更改var引用,外部作用域中的var会被准确地更新-正如您的意图一样。
这就是_matchIds
保持为空的原因:每次调用makeRequestV2时,内部变量matchesArray
都会从外部作用域“去接触”(在赋值语句执行期间),尽管它被填充了,但外部作用域的变量仍然指向原始引用并保持不变。
https://stackoverflow.com/questions/57447189
复制相似问题