2014-05-22 70 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 
    }); 
    }); 
});