// promise allows us to write code for situations which say "when all of these things have happened do this one more thing". Promise is an object that is initially in a pending state and then can go to resolved(success) or rejected(failure) state. Once a promise reaches resolved or rejected state, it will remain in that state forever and its callbacks will not fire again.
// a deferred object is like a promise with methods that allow its owner to resolve or reject. A promise object doesnt have methods that allow its owner to resolve or reject. Hence promise is a deferred object with resolve() and reject() methods missing. By calling deferred.promise() we can get hold of the promise object.
// jquery's ajax methods do the same. They return a promise object so that the caller can not resolve or reject it. It would be odd if the caller was allowed to determine whether the ajax was successful or failed.
// once we have a promise object we can attach as many callbacks as we like using done(), fail() and always() methods
var divLoading = $("#divLoading");
divLoading.hide();
var container = $("#container");
var successFunc = function() {
container.append("both calls succeeded");
divLoading.hide();
};
var failureFunc = function() {
container.append("one or both calls failed");
divLoading.hide();
};
$("#btnLoad").click(function() {
divLoading.show();
// execute a function after 2 ajax requests are successful or failed
// here we have 2 promises. The successFunc is called if both promises are succesful. failureFunc is called if either one or both promises fail.
// then is providing the success and failure callbacks
$.when($.ajax("/somerequest"), $.ajax("/someotherrequest")).then(successFunc, failureFunc);
});
// this example shows how we can chain multiple success and failure functions. In current ajax method we can only specify one success and failure.
var container1 = $("#container1");
$("#btnLoad1").click(function() {
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.