N asynchronous requests, plus plain-old function as deferred with jQuery
by b_long
HTML
<body class="put-stuff-here">
<h4><u>Log</u></h4>
</body>
JavaScript
var allUsers = ['john', 'ringo', 'paul', 'george'],
masterIndex = 0,
lastUserModified = null,
logIt = function (msg) {
$(".put-stuff-here").append("<pre>" + ((new Date()).toLocaleTimeString()) + ": " + msg + "</pre>");
}, getAjaxConfiguration = function () {
return {
type: 'POST',
url: '/echo/json/',
success: function (data) {
var msg = "" + data.message + data.u;
logIt("AJAX success handler: " + msg);
}
};
}, async1 = function (userToCreate) {
return $.ajax($.extend(getAjaxConfiguration(), {
data: {
json: JSON.stringify({
serviceNumber: 1,
u: userToCreate,
message: "Created user: ",
description: "Service #1's data"
}),
delay: 0 // delay on the server-side
}
}));
}, async2 = function (userToModify) {
return $.ajax($.extend(getAjaxConfiguration(), {
data: {
json: JSON.stringify({
serviceNumber: 2,
description: "Service #2's data",
u: userToModify,
message: "Modified user: "
}),
delay: 0 // delay on the server-side
}
}));
};
var do2AsynchronousFunctions = function (userN, indexValue) {
var dfd = new $.Deferred();
async1(userN)
.then(function (retVal1) {
logIt("async1's then() method was called. retVal1 = " + JSON.stringify(retVal1));
async2(userN)
.then(function (retVal2) {
lastUserModified = retVal2.u;
logIt("async2's then() method called. retVal = " + JSON.stringify(retVal2));
}) // end of async2's then()
.fail(function () {
logIt("\n\nERROR in async2");
}) // end of async2's fail()
...