tags:

views:

68

answers:

3

I have some code that does this:

function A(){
    $.ajax({
        ...blah blah...
        success: function(data){
            return data;
    });
 }

and then I'm trying to use the data later:

var x = A();
x.doSomething();

but x is never stored, since A() takes a while. Is there any way to avoid this?

A: 

Why not manipulate data inside of the callback?

meder
A: 

Taking meder's answer and extending it:

Why not take action immediately on success, as in:

function A()
{
  $.ajax
  (
    {
      success: function(data)
      {
        data.doSomething();
      }
    }
  );
}
David Andres
+1  A: 

Other Questions about the same topic:

I'm sure there are more. However the advice in all of them will boil down to two paths to take.

Pass a callback down the line

function A(callback){
    $.ajax({
        //...blah blah...
        success: function(data){
          if (typeof callback == 'function') callback(data);
        }
    });
 }

 // passing our function through will cause it to be called after the data
 // is received
 A(function(data) {
  data.doSomething();
 });

Making your AJAX Synchronous

This option seems easier, but it will also block all script execution while it waits for your AJAX request, and therefore is not as desireable

function A() {
  var retValue;
  $.ajax({
    async: false,
    success: function(data){ 
      retValue = data;
    }
  });
  return retValue;
}

var x = A();
x.doSomething();
gnarf