jQuery deferred example fixed
This example show how to correctly work with jQuery deferred object
by Akram kamal
HTML
<p>I expect to read below: "Final rejection handler hit" and to see no "Uncaught
error" messages into the console</p>
<div id="container"></div>
JavaScript
// fulfillPromiseAsync is simply resolving the promise after 100msec to simulate an async operation
function fulfillPromiseAsync() {
var d = $.Deferred(function (d) {
setTimeout(function () {
d.resolve("Ok");
}, 100);
});
return d.promise();
}
// Simulating the case where the original promise is fulfilled, the fulfillment handler throws an exception: getting data, and throwing an exception in response to it
fulfillPromiseAsync()
.then(
function (msg) { // I only add a fullfillment handler for simplicity as I know fulfillPromiseAsync will always resolve its promise
var d = $.Deferred();
if (msg === "Ok") {
d.reject("I want you to fail");
} else {
d.resolve("Still ok");
}
return d.promise();
})
.then(
function (msg) { // end of the chain fullfillment handler
var d = $.Deferred();
console.log("Final fullfillment handler");
$("#container").html("Final fullfillment handler hit");
d.resolve();
return d.promise();
},
function (err) { // end of the chain rejection handler
var d = $.Deferred();
console.log("Final rejection handler: " + err);
$("#container").html("Final rejection handler hit");
d.resolve();
return d.promise();
});