-2

This can be considered a general programming question or even logic question, as it's language independent.

I have the following piece of code in JavaScript:

...
{text: 'Modelo', dataIndex: 'model', filterable: true,
    renderer: function(value) {

        // this will asynchronously load the object "Model" from the database which have primary key equals to "value".
        MyApp.model.Model.load(value, {
            scope: this,
            success: function(record, operation) {
                // this will be executed if succeeded. I need to return the "record" parameter in the outer function.
            }
        });
        return value; // There must be a way to return the "record" parameter from above.
    }
}, 
...

As stated in the comments, there's the outer function renderer that calls an inner asynchronous function load that retrieves the value record I need to return from the outer function.

I tried ugly things like an empty while-loop waiting for a variable declared in the outer function to be set in the inner function and then return it, but no success, the loop ended up being infinite.

Bruno Finger
  • 2,105
  • 3
  • 27
  • 47
  • See [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) and [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call). Short answer: you can't return the value, use a callback or promises. – Felix Kling Jul 21 '14 at 20:15
  • Why there must always be a downvote? I don't know why I keep returning to this website to ask for help, I am asking a legitimate question and downvoting only makes me feel that it's a stupid question and that people are less willing to help. Remember what teachers said back in school? _Don't be afraid to ask_. This website is not like this. That's why I am sure the old "forum" style ask-and-answer worked better. – Bruno Finger Jul 22 '14 at 13:28

1 Answers1

0

You can't return directly as the success callback fires after the return has occurred. Instead you can continue this callback pattern in your code... if you change the function signature of renderer to accept a callback:

{text: 'Modelo', dataIndex: 'model', filterable: true,
    renderer: function(value, successCb) {    
        MyApp.model.Model.load(value, {
            scope: this,
            success: function(record, operation) {
                if(successCb){
                    successCb(record, operation);
                }
            }
        });
        //return void, and communicate back to the caller using successCb above.
    }
}, 

and the caller of renderer supplies a callback:

myObj.renderer(someVal,function(rec,op){
    //do something
});

now you can get data out of your function asynchronously.

spender
  • 117,338
  • 33
  • 229
  • 351