mysql - Node JS 嵌套函数和变量作用域

标签 mysql node.js scope

是否有一种方法可以将变量传递给嵌套回调,而不必将它们传递给每个函数?问题是我需要调用 getValueFromTable1 来获取数据库的一个值。获取该结果并从原始列表中添加另一个变量,并将其发送到 getValueFromTable2 以从数据库获取第二条信息,然后最后从顶级函数中获取带有 userID 的 result2 并使用它来执行数据库插入。

我知道我可以使用连接等进行更复杂的数据库查询,以便我一次获取所有信息,然后只调用一个函数,但我的“getValueFromTable1”和“getValueFromTable2”是通用函数,它们获取一组我可以在多个地方重复使用数据库中的数据,这就是为什么我尝试这样做。

我遇到的问题是,当我调用时, Node JS 在范围内没有 itemList

itemList[i].item2

我不会将 item2 传递给 function2,因为 function2 不需要它来实现其自身目的,并且它会使其采用不需要的变量。

doDatabaseInsert(itemList, userID) {

  for(var i=0; i < itemList.length; i++) {

    getValueFromTable1(itemList[i].item1, function(results) {

      getValueFromTable2(results, itemList[i].item2, function(results2) {

        //Finally do stuff with all the information
        //Do DB insert statement with userID, and results2 into table 3
      }
    }
  }
}

最佳答案

您无法使用常规 for 循环来执行此操作,因为您是从异步回调内部引用 i,其中 i 的值已经是 itemList .length 因为 for 循环很久以前就结束了。

试试这个:

itemList.forEach(function(item) {

  getValueFromTable1(item.item1, function(results) {

    getValueFromTable2(results, item.item2, function(results2) {

      //Finally do stuff with all the information
      //Do DB insert statement with userID, and results2 into table 3
    });
  });
});

关于mysql - Node JS 嵌套函数和变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23810133/

相关文章:

php - 存储获取和存储IP地址

mysql - 通过mysql还是rails在数据库之间传输记录更好?

node.js - Sequelize.js - 按关系 ID 列表查找对象

node.js - Angular 2+ 中客户端和服务器之间的通信

javascript - 类似于 c++ 中用于 javascript 的基于堆栈的对象

sql - 来自 3 个相关表的 MySQL JOIN

php - 如何在特定列上动态打印列子标题?

javascript - 如何填充嵌套虚拟?

java - ArrayList不同方法的作用域

c++ - Boost.Python - 如何重新进入模块范围?