【发布时间】:2019-04-30 12:30:59
【问题描述】:
我正在尝试使用 for 循环为来自 API 调用的每个响应创建一个文件,但是当我尝试使用互操作时,它会给出错误:
i 未定义,即使它在循环使用它进行 API 调用时已定义
function sysWrite(data){
fs.appendFile(`${testArray[i}[1]}.json`, data, function(err){
if(err) throw err;
})
}
forLoop().then(function (resSet){
for(i = 0; i < resSet.length; i++){
(function(i){
setTimeout(function(){
axios.get(`https://api.census.gov/data/2016/acs/acs5?get=NAME,${resSet[i]}&for=state:*&key=${censusAPI}`)
.then(function (response) {
//problem place
let replacedKey = Object.assign({}, response.data);
let jsonData = JSON.stringify(replacedKey).replace(testArray[i][0], testArray[i][1]);
sysWrite(jsonData)
})
.catch(function (error) {
console.log(error);
});
}, 100*i)
})(i);
}
})
【问题讨论】:
-
i未在sysWrite中定义。该函数如何知道i是什么?您在该字符串模板中也有一个看似错误(两端大括号)。 -
我不知道该函数如何知道
i是我的问题,我尝试过的一切都没有奏效。你有什么建议
标签: javascript node.js fs