In jquery, deferred is a chainable utility which is introduced in jquery 1.5 and it is created by calling jquery.Deferred() method. This code is used to register callbacks into callback queues and checks the success status of any synchronous and asynchronous function.
<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script>
function fulfillPromiseAsync() {
var d = $.Deferred(function (d) {
setTimeout(function () {
d.resolve("Ok");
}, 100);
});
return d.promise();
}
fulfillPromiseAsync()
.then(
function (msg) {
var d = $.Deferred();
if (msg === "Ok") {
d.reject("Fail");
} else {
d.resolve("Ok");
}
return d.promise();
})
.then(
function (msg) {
var d = $.Deferred();
console.log("Final handler");
$("#container").html("Final handler hit");
d.resolve();
return d.promise();
},
function (err) {
var d = $.Deferred();
console.log("Rejection handler: " + err);
$("#container").html("Rejection handler hit");
d.resolve();
return d.promise();
});
</script>
<p>Here,"there occurs Rejection handler hit" and see error in the console log. </p>
<div id="container"></div>