javascript - 使用 FOR 循环为来自 API 调用的每个响应创建一个文件
问题描述
我正在尝试使用 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);
}
})
解决方案
问题:
在“sysWrite”函数中,该函数引用了在当前上下文中未定义的“testArray[i][1]”。
此外,“sysWrite”函数有一个错字,上面写着“ ${testArray[i}[1]}.json
”,应该有${testArray[i][1]}.json
(你用花括号而不是方括号封闭了数组索引)。
简单解释:
当您调用“sysWrite”时,您的所有局部变量在该上下文中都不存在。
这是了解变量的一个很好的参考: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
简单的解决方案:
function sysWrite(name, data){
fs.appendFile(`${name}.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(testArray[i][1], jsonData);
})
.catch(function (error) {
console.log(error);
});
}, 100*i)
})(i);
}
})
推荐阅读
- python - 为什么在我可以重用打开的端口之前会有时间延迟?
- apache - mod_rewrite 编码后的url?
- javascript - Vue.Js:如何在 JSON 中循环子对象
- django - 如何从反向外键 Django 序列化程序(一对多)中获取所有相关对象?
- javascript - 为什么 WebGL 使用 GLSL 代码块的字符串表示?
- xamarin.forms - 退出前在主详细信息页面上确认
- sql - 多选时如何过滤掉重复的列(SQL Server)
- c++ - 计算两个 uint8_t 变量之间差异的最快方法是什么?
- android - 错误:格式字符串不是字符串文字(可能不安全)[-Werror,-Wformat-security]
- css - 具有响应宽度和连续两个按钮的输入