Reputation: 58
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 ?
Upvotes: 0
Views: 103
Reputation: 5060
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
});
Upvotes: 1
Reputation: 658
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.
Upvotes: 0
Reputation: 341
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;
}
});
Upvotes: 0