1

This is the function that is supposed to return name :

function getLookupNameById(lookup_id, callback){
    var name = "";
    if(lookup_id != 0) {
        updateData({
            lookup_id: lookup_id,
            callback: function(status, data){
                if( status && data.values){
                    values =  data.values;
                    name = somevalue;
                    return name; //returns undefined
                }
                else{
                    console.log('Empty');
                }
                if(callback)
                    callback();
            }
        });
    }
    return name; //returns empty string
}

This is how i am calling the function from another script :

var name = instanceofscript.getLookupNameById(parameter);

How should i return the value??

varun257
  • 296
  • 2
  • 17

1 Answers1

2

When you use asynchrnonous functions, you can't return anything from them, since they don't run until after the caller returns. Everything that depends on the returned data has to be done in the callback function.

The callback function should receive name as a parameter:

if (callback) {
    callback(name);
}

And then you need to call it like this:

instanceofscript.getLookupNameById(parameter, function(name) {
    console.log(name);
});

This is essentially the same as using AJAX, so see How do I return the response from an asynchronous call?

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612