0

I have a function that internally makes ajax call and has success and failure callback method.

function dothis() {
    object.getMyData(x,y,successCallback,failureCallback);
}

the function returns immediately since getMyData is an async one . Now i want the function dothis to wait until successCallback or failureCallback is executed . How to do it using deferred ?

DrColossos
  • 12,656
  • 3
  • 46
  • 67
Dav
  • 58
  • 1
  • 7

3 Answers3

1

ajax already returns a deferred, so you could just use that. Can you change getMyData to return the deferred that ajax returns?

function getMyData() {
    return ajax({
        // ajax params
    });
}

function dothis() {
    // return deferred which comes from ajax
    return object.getMyData(x,y,successCallback,failureCallback); 
}

dothis().done(function(){
    // do something on success
}).fail(function(){
    // do something on failure
});

If you can't change getMyData to return the deferred, you can do this:

function dothis() {
    var dfd = $.Deferred();
    object.getMyData(x,y,function(){
        dfd.resolve(); // success
    },function(){
        dfd.reject();  // fail
    });
    return dfd.promise(); 
}

dothis().done(function(){
    // do something on success
}).fail(function(){
    // do something on failure
});
Paul Hoenecke
  • 5,060
  • 1
  • 20
  • 20
0

It looks like you don't need an asynchronous call.

Did you try to do a sync call and then perform the success/failure function ? Please clarify.

Thanks,

@leo

Sync Call Example>

$.ajax({
        type: "GET",
        url: remote_url,
        async: false,
        success : function(data) {
            remote = data;
        }
    });
lemil77
  • 341
  • 1
  • 8
0

I preferr you to use $.when and $.then combination of jquery deferred.

You can visit this

You can also found relative answer in stackoverflow too.

Community
  • 1
  • 1
Bilal lilla
  • 618
  • 3
  • 8
  • 29