Promises and Deferreds
by karim79
JavaScript
// A simple example.
function wait(ms) {
var deferred = $.Deferred();
setTimeout(deferred.resolve, ms);
// We just need to return the promise not the whole deferred.
return deferred.promise();
}
// Use it
wait(1500).then(function () {
console.log("I'm done waiting");
});
// synchronise parallel tasks
var promiseOne, promiseTwo, handleSuccess, handleFailure;
// Promises
promiseOne = $.ajax({
url: '/echo/html/',
type: 'post',
data: { html: "<em>Some crazy cool HTML</em>", delay: 3 }
});
promiseTwo = $.ajax({
url: '/echo/html/',
type: 'post',
data: { html: "<em>More crazy cool HTML</em>" }
});
// Success callbacks
// .done() will only run if the promise is successfully resolved
promiseOne.done(function (html) {
console.log('PromiseOne Done ' + html);
});
promiseTwo.done(function (html) {
console.log('PromiseTwo Done' + html);
});
// $.when() creates a new promise which will be:
// resolved if both promises inside are resolved
// rejected if one of the promises fails
$.when(promiseOne, promiseTwo)
.done(function () {
console.log('Cool, both requests are done now');
}).fail(function () {
console.log('One of our promises did not fulfill');
});