JQuery: waiting for a callback before returning

I have a javascript function that requests some ajax data and returns a JSON object. Then it must return the object.

The problem is that I don't know how to return a function from an Ajax callback. Of course,

myFunction: function() { $.get(myUrl, function(data) { return data; }); } 

does not work because the internal function is returned instead of the external.

On the other hand, doing what I need only inside the callback will violate my MVC unit: this code is in the model, and I wanted to use the result object in the controller.

Workaround Workaround

 myFunction: function() { var result = $.ajax({ url: myUrl, async: true, dataType: 'text' }).responseText; return eval(result); } 

which has the disadvantage of blocking the browser, waiting for a response (and using eval, which I would prefer to avoid).

Are there any other solutions?

+6
jquery asynchronous callback return
source share
2 answers

You can simply pass a callback to your function to process the data when it is ready:

 myFunction: function(callback) { $.get(myUrl, function(data) { callback( data ); }); } 
+9
source share

Why do you want to return an object? If you intend to use this object after, the best way would be to include the function using the data in the callback.

+1
source share

All Articles