2014-05-22 73 views
0

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

我知道我可以做一个更复杂的数据库查询与联合等,以便我一次获得所有的信息,然后只调用一个函数,但我的“getValueFromTable1”和“getValueFromTable2”是泛型函数,获得一组我可以在多个地方重复使用数据库中的数据,因此我试图以这种方式进行操作。

我得到的问题是,节点JS不具有itemList中时,我打电话

itemList[i].item2 

而且我不是过客ITEM2到函数2,因为函数2不需要它来达到自己的目的,它的范围会使它变成一个不需要的变量。

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 
     } 
    } 
    } 
} 

回答

0

你不能做到这一点与for循环有规律,因为你是从一个异步回调,其中i值已经itemList.length因为for循环结束前不久内引用i

试试这个:

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