jQuery deferred broken example
This example is a proof scenario to demonstrate that jQuery promise implementation is broken
HTML
<script src="http://media.digitalxero.net/jquery.min.js"></script>
<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
if (msg === "Ok") {
throw new Error("I want you to fail");
} else {
console.log("Still ok");
}
})
.then(
function (msg) { // end of the chain fullfillment handler
console.log("Final fullfillment handler");
$("#container").html("Final fullfillment handler hit");
},
function (err) { // end of the chain rejection handler
console.log("Final rejection handler: " + err);
$("#container").html("Final rejection handler hit");
});