首页 > 解决方案 > 使用 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);
  }
})

标签: javascriptnode.jsfs

解决方案


问题:

在“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);
  }
})

推荐阅读