Jason Jason - 7 months ago 34
Javascript Question

JQuery Promises on An Asynchronous Dialog

This is a followup to a question I asked yesterday. I'm having a different problem related to jquery promises.

function setOverrides2() {
var dfd = new $.Deferred();
// do something
return dfd.promise();
}

function overrideDialog1() {

var deferred = new $.Deferred();

ConfirmMessage.onConfirmYes = function() {
ConfirmMessage.hideAll();
// do stuff
deferred.resolve();
}

ConfirmMessage.onConfirmNo = function() {
ConfirmMessage.hideAll();
// do stuff
deferred.reject();
}

ConfirmMessage.showConfirmMessage("Do you wish to override primary eligibility?");

return deferred.promise();

}

function overrideDialog2() {

var deferred = new $.Deferred();

ConfirmMessage.onConfirmYes = function() {
ConfirmMessage.hideAll();
// do stuff
deferred.resolve();
}

ConfirmMessage.onConfirmNo = function() {
ConfirmMessage.hideAll();
// do stuff
deferred.reject();
}

ConfirmMessage.showConfirmMessage("Do you wish to override secondary eligibility?");

return deferred.promise();
}

setOverrides2().done(function(data) {

// shows both dialogs at once
overrideDialog().then(overrideDialog2()).then(function() {
alert("test");
});

// waits for one dialog to complete before showing the other
// overrideDialog1().done(function() {
// overrideDialog2().done(function() {
// alert("test two!");
// });
// });
});


As shown above, when I use done(), it works perfectly, but when I use then(), it shows both dialogs simultaneously. I want to be able to be able to use reject() to abort the chain the first time the user clicks the No button (defined by the onConfirmNo() callback).

The commented .done() section waits for one dialog to finish before triggering the next, but does not abort processing if the user clicks No on the first dialog.

I think I almost have this right, so if anyone can assist on this last piece of the puzzle, I'd greatly appreciate it.

Jason

Answer
overrideDialog().then(overrideDialog2())

Should be:

overrideDialog().then(overrideDialog2)

The reason done was working was because you wrapped it inside a function (which did not immediately execute)