HTML and CSS Reference
In-Depth Information
is invoked. If an error occurred, the promised would be set to the state of “failed”, and the
relevant callback would be invoked (“fail”).
There are several advantages to using promises over traditional callbacks, both in this
AJAX example, and in your own libraries. The first is that it is possible to add multiple
success or failure callbacks:
promise = $.ajax({
type : "GET",
url : "/server/tasks.json",
cache : false
});
promise.done(function(data) {
console.log(data);
});
promise.done(function(data) {
console.log('Also do this');
});
promise.fail(function() {
console.log('A failure occurred');
});
Secondly, even after the AJAX call has finished, you can still call done and fail to register
callbacks, and these will be executed immediately. This may not sound useful, but consider
a case where we do not know if a call will be synchronous or asynchronous.
This may happen in cases where we are caching data on the client: if the data is cached it
will be available synchronously, otherwise it will be available asynchronously. This means
that when we add a callback, the result may be available immediately, and the promise
will actually have been fulfilled when we register our callback. An example of this will be
provided below.
The third major benefit of promises is that it is possible to delay a callback until multiple
promises have completed. This may be useful if you need to perform multiple AJAX calls,
aggregate the data, and update the DOM:
promise1 = $.ajax({
url : "/server/tasks.json",
});
promise2= $.ajax({
Search WWH ::




Custom Search