michele michele - 4 months ago 12
jQuery Question

Using deferred in jquery asynch POST call

I have a button with this event:

$("#getSensorsObs").click(function (e) {
e.preventDefault();
postCallOne();
postCallTwo();
});


I want
postCallTwo
fire when postCallOne has completed with success the first call.

function postCallOne() {
setWait();
//do something

return $.post(ADDRESS, {fieldONE : fieldOneVal })
.done(function (data) {
console.log("RESPONSE SUCCESS ");
// do something

}).error(function(x, t, m) {
alert(x + ' ' + t + ' ' + m);
}
}).then(function (resp) {
return $.Deferred(function(def){
def.resolveWith({},[resp == 1,valueSelected]);
}).promise();
});


This is the second function:

function postCallTwo() {
setWait();
//do something

return $.post(ADDRESS2, {fieldONE : fieldOneVal })
.done(function (data) {
console.log("RESPONSE SUCCESS ");
// do something

}).error(function(x, t, m) {
alert(x + ' ' + t + ' ' + m);
}
});
});


I have tried with:

$("#button").click(function (e) {
e.preventDefault();
postCallOne.then( function(){postCallTwo();});

});


But I have returned postCallOne.done is not a function.

I don't know very well Deferred, who can help me?

Thanks a lot.

Answer

You need to call it like this:

$("#button").click(function (e) {
    e.preventDefault();
    postCallOne().then(function() {postCallTwo()};);

});

The problem with the way you have written is the call to postCallTwo will be placed before the deferred is resolved from postCallOne. You need to wait for postCallOne to resolve and then you chain postCallTwo on the success of postCallOne. That's the reason deferreds exist.