2015-11-04 60 views
1

我有這個遞歸函數,我需要的功能完成後返回一些數據返回的JavaScript數據。我如何從一個函數使用遞歸調用

// Set Up my Database paramaters 
var coachdb = new AWS.DynamoDB({ 
    ... 
}); 

// This tracks the array index of the current parameter. 
var pos = 0; 

function callback(err, data) { 
    if (err) { 
    console.log(err, err.stack); 
    } else if (data.Items.length > 0) { 

    //return data.Items // Where I need something here to return data 

    } else if (++pos < params.length) {  // Increment the index. 
    coachdb.query(params[pos], callback); // Recursive call. 
    } 
} 

coachdb.query(params[pos], callback); // Kick off the series of calls 

函數內部的一切工作正常。我正在查詢我的數據庫,只需遍歷可能的參數,直到找到正確的參數,然後函數結束。

但是我不知道如何傳遞功能之外的數據。任何幫助,將不勝感激。

回答

2

這是不可能的,而不是返回你需要寫回調裏面的邏輯數據。

編輯:如果你不希望有您需要重構你的代碼和提取代碼單獨的方法亂碼;

function callback(err, data) { 
    if (err) { 
    errorLogic(err); 
    } else if (data.Items.length > 0) { 
    successLogic(data.Items); 
    } else if (++pos < params.length) {  // Increment the index. 
    coachdb.query(params[pos], callback); // Recursive call. 
    } 
} 
+0

我該怎麼辦呢?這會是一個很好的方式來做這樣的事情,還是會太雜亂? –

+0

@JaredWhipple檢查我的編輯 – Almis

0

另一個想法是使用承諾來規避回調的需要。看看納米,例如(http://www.mircozeiss.com/async-couchdb-queries-with-nano-and-promises/)。從本質上說,你有一個對象,將「在一段時間內」包含你的數據庫,在這個時間點的事件函數被調用的數據。

僞代碼:

var myPromise = couchdb.insert(...); 

myPromise.success(function (mydata){ 
    // here you can fiddle around with your data 
})