Ashish Agarwal
Ashish Agarwal

Reputation: 6283

How to get value returned by Callback function?

Here is my piece of code am trying:

initData:function(period)
{    
    this.getLoadObject('0',url, this.callbackFunction);
},

I want to receive a return value from callBackFunction, which I want to be returned by initData.

Can any body help me, am not so proficient with JS. I tried similar question but didn't get help.

Upvotes: 1

Views: 7041

Answers (3)

herostwist
herostwist

Reputation: 3958

Although it's impossible to tell from your code snippet, it looks like your callback function will be called asynchronously. if this is the case you will need to set variables that you want to be populated by initData within the callback function itself.

you could also wrap the callback function:

    var context = this;
    this.getLoadObject('0',url, function() {
       var returnedval = context.callbackFunction.apply(context,arguments);
       context.SomeFuctionToUseValue(returnedval);
    });

Upvotes: 1

2GDev
2GDev

Reputation: 2466

I think you could use variable outside the function, so you can access it inside the callback function and outside.

var result = false;
initData:function(period)
{   
   this.getLoadObject('0',url, this.callbackFunction);
   //inside the callback you can modify the "result" then
   return result;
},

Upvotes: 0

Maurice Perry
Maurice Perry

Reputation: 32831

Actually, the callback function may very well be called asynchronously, that is after the return from the call to initData.

If it is synchronous however, you can do this:

initData:function(period)
            {   
                var that = this;
                var result;
                this.getLoadObject('0',url, function() {
                    result = that.callbackFunction(arguments));
                });
                return result;
            },

Upvotes: 2

Related Questions