0

I am trying to return the value of itemInfo[0] from within this nested function. Can anyone help how I should return this value with a callback ?

function findItem(item) {

  var itemInfo = [];

  Item.findItem(item, function(err, itemInfo){
    itemInfo[0].info = _.unescape(itemInfo[0].info);
    itemInfo[0].title = _.unescape(itemInfo[0].title);
    // console.log(itemInfo[0]);
    return itemInfo[0];
  });

};

2 Answers2

4

Set the cb argument to null after you use it and check for its validity before calling.

function findItem(item, cb) {

  var itemInfo = [];

  Item.findItem(item, function(err, itemInfo){
    if (cb) {
        itemInfo[0].info = _.unescape(itemInfo[0].info);
        itemInfo[0].title = _.unescape(itemInfo[0].title);
        // console.log(itemInfo[0]);
        cb( itemInfo[0] );
        cb = null;
    }
  });

};
jeremy
  • 4,294
  • 3
  • 22
  • 36
  • 1
    Why set it to `null`? – Pointy Nov 12 '13 at 03:30
  • There are a few ways to do it, you could also just keep a variable "found" or something. I like setting it to null because you can't accidentally call the callback twice and `cb = undefined` is all kinds a trouble. – jeremy Nov 12 '13 at 03:31
  • How in this case could the code possibly end up trying to call it twice? I guess it might depend on what `findItem` does. – Pointy Nov 12 '13 at 03:33
  • In this case, it wouldn't. I just code defensively, just thinking about future cases – jeremy Nov 12 '13 at 03:34
  • 1
    It will return undefined because you have an async "findItem". You'll need to call `findItem(item, function(foundValue) { ... do something ... });` – jeremy Nov 12 '13 at 03:36
-3

What if you returned the returned value?

function findItem(item) {

     var itemInfo = [];

     return Item.findItem(item, function(err, itemInfo){
        itemInfo[0].info = _.unescape(itemInfo[0].info);
        itemInfo[0].title = _.unescape(itemInfo[0].title);
        // console.log(itemInfo[0]);
        return itemInfo[0];
     });

 };
asiviero
  • 1,225
  • 10
  • 16
  • 1
    Callbacks do not return values because there is nothing into which they can. You need to think about callbacks as being independent of traditional program flow, because they are called as needed rather than as a part of any kind of sequential process. – Rob Raisch Nov 12 '13 at 23:36