【发布时间】:2018-11-29 13:38:03
【问题描述】:
我想从 API 访问一些数据,但遇到了问题。我的代码正在从 API 中获取一些数据,并将其与 API 的本地副本进行比较。如果本地副本与从 API 获取的副本不匹配,我希望它在数组中存储一些数据。获取和比较工作正常。当我尝试填充数组并想将其归还时,问题就出现了。 request 函数是异步的,所以我最后的返回值将是未定义的。我的函数checkForDiff 应该在 for 循环完成后返回这个数组,因为在 for 循环之后数组应该填充我需要的信息。我是 Nodejs 的新手,所以我真的不知道如何解决它。我需要在返回之前填充数组,但是异步 request 调用给我带来了问题。我怎样才能实现这种行为?
提前感谢您的帮助
function checkForDiff(){
let outdatedLanguages = [];
var options = {
url: 'https://xxxxxxxxxxxxxxxxxxxxxxxxx',
headers: {'Key': 'xxxxxxxxxxxxxxxxxxxxxx'}
};
for(let index = 0; index < locales.length; index++){
//Change url for new https request
options.url = `https://xxxxxxx?locale=${locales[index].symbol}`
//Send new https request to API
request(options, (error, response, body)=>{
var localState = hash(JSON.parse(filesystem.readFileSync(`./cards/cards-${locales[index].symbol}.json`)));
var recentState = hash(JSON.parse(body));
/If the local card base is not up to date, add locale to array
if(localState !== recentState){
outdatedLanguages.push(locales[index].symbol);
}
);
}
//Return outdatedLanguages array
return outdatedLanguages;
}
【问题讨论】:
标签: javascript node.js asynchronous