1

I have this recursive function where I need to return some data after the function completes.

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

Everything inside the function is working just fine. I am querying my database just fine iterating through the possible parameters until the right one is found and then the function ends.

However I am not sure how to pass the data outside the function. Any help would be appreciated.

Jared Whipple
  • 1,111
  • 3
  • 17
  • 38

2 Answers2

2

It's not possible, instead of returning the data you need to write your logic inside the callback.

EDIT: If you don't want to have messy code you need to refactor your code and extract code to separate methods;

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.
  }
}
Almis
  • 3,684
  • 2
  • 28
  • 58
0

another idea would be the usage of promises to circumvent the need for the callback. Take a look at nano, for example (http://www.mircozeiss.com/async-couchdb-queries-with-nano-and-promises/). In essence, you have an object that will 'at some time' contain the data of your database and at this point in time an event function is called.

pseudocode:

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

 myPromise.success(function (mydata){
    // here you can fiddle around with your data
 })
PlasmaLampe
  • 129
  • 2
  • 12