$.Deferred play
by fiddlegrimbo
JavaScript
function get(s, delayInSecs) {
var promise = $.ajax("/echo/html/", {
type: "POST",
data: {
delay: delayInSecs,
html: s
}
});
return promise.then(function() {
console.log("get()", "response after " + delayInSecs + "s");
// http://api.jquery.com/jQuery.ajax/ ...
// "The 'this' reference within all callbacks is the object in the
// context option passed to $.ajax in the settings; if context is
// not specified, 'this' is a reference to the Ajax settings themselves."
console.log("get()", "this=", this, "arguments=", arguments);
return promise;
});
}
function filterJQXHRData(filter) {
return function() {
// Save the original data.
var data = arguments[0];
var status = arguments[1];
var jqXHR = arguments[2];
// Perform the filter.
var newData = filter(data);
// Return a new promise that retains the old args, but replaces the new data.
// Does this work for jqXHR errors?
return $.Deferred(function(dfd) {
return dfd.resolve(newData, status, jqXHR);
}).promise();
};
}
function createLowerCaseString(num) {
var A = 97;
var s = "";
for (var i = 0; i < num; i++) {
s += String.fromCharCode(A + Math.random() * 26);
}
return s;
}
// Converts a function and delay into a promise.
// The function will be executed after delayInMillis ms.
function createAsync(fn, delayInMillis) {
delayInMillis = delayInMillis || 0;
return $.Deferred(function(dfd) {
setTimeout(function() {
console.log("createAsync() response after " + delayInMillis + "ms");
dfd.resolve(fn());
}, delayInMillis);
}).promise();
}
function printArgs() {
console.log(arguments.length, arguments);
}
function random(max) {
return Math.floor(Math.random() * max);
}
function toUpperCase(s) {
return...