0

I want to return a value from nested functions in my cordova/javascript application with some plugins, but it doesn't work as supposed:

if(restaurantsNearby == true) {
    if(restaurantNameArr.length == 1){
        return restaurantNameArr[0].rID;
    } else {
        return actionSheet(restaurantNameArr);
    }
}

var actionSheetCallback = function(buttonIndex) {
    return window.restaurantNameArr[buttonIndex-1].rID;
};

function actionSheet(restaurantNameArr) {
    var restaurantNames = new Array();
    $.each(restaurantNameArr, function(key, value) {
        restaurantNames.push(value['rName']);
    });
  var options = {
    'title': 'Where are you?',
    'buttonLabels': restaurantNames,
    'androidEnableCancelButton': false,
    'winphoneEnableCancelButton': false
  };
  window.restaurantNameArr = restaurantNameArr;
  window.plugins.actionsheet.show(options, actionSheetCallback);
  return actionSheetCallback;
};

I want to return the value of window.restaurantNameArr[buttonIndex-1].rID with the first if-statement, but it doesn't work.

EDIT restaurantNameArr looks like [{rID: '188', rName: 'Taverne'}, {rID: '192', rName: 'Pub'}, {rID: '193', rName: 'Ducis'}, ...]

John Brunner
  • 2,842
  • 11
  • 44
  • 85

1 Answers1

0

You are saying the object is

{ rid : { rid : {} } }

it is probably not nested like that. Drop the rid

if(restaurantNameArr.length == 1){
    return restaurantNameArr[0]; //.rID;
} else {
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • it is nested like this -> `[{rID: '188'}, {rID: '192'}, {rID: '193'}, ...]` – John Brunner Mar 02 '15 at 16:39
  • I know, but that is not how you have coded it. You return the rid and than you try to read the rid again. And when there is only one, you do not return an array so that would be an issue also. – epascarello Mar 02 '15 at 16:43
  • thanks for your comment but actually i have a problem with `return actionSheet(restaurantNameArr);`, the other code snippet works fine – John Brunner Mar 02 '15 at 16:58
  • @epascarello is your callback being called in a Asynchronous function, then it will not work. You cannot return a value from an Asynchronous function. check this [link](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) for returning values from Asynchronous function. – frank Mar 02 '15 at 17:13
  • @frank Where is there an Asynchronous in that code? – epascarello Mar 02 '15 at 17:59
  • @epascarello My mistake, I wanted it to address it to @JohnBrunner. I was just cautioning him(@JohnBrunner). That if he is using a Async func than it will not work. Most of the times the OP does not post the true picture of their problem. Also if you see the last line in the code `window.plugins.actionsheet.show(options, actionSheetCallback); return actionSheetCallback;` he trying to to return from a callback. Which I presume that the function `show()` is an Asycn function call. – frank Mar 03 '15 at 07:46