JSFiddle - React, Tailwind, and code Playground
HTML
<div id="left">
<h1>Using chained promises</h1>
</div>
<div id="right">
<h1>Using response caching</h1>
</div>
CSS
#left {
float: left;
width: 50%;
}
#right {
float: right;
width: 50%;
}
h1 {
font-size:2em;
}
body {
font-family: Helvetica, Verdana, Arial, sans-serif;
}
JavaScript
/* METHOD 1 */
var i, promises = [];
for (i = 0; i < 10; i++) {
promises.push($.ajax({
url: '/echo/html/',
data: {
html: '<h2>Left response number ' + i + '</h2>',
delay: Math.floor(Math.random() * 4 + 1)
},
type: 'post'
}));
(function serialize() {
var def = promises.shift();
if (def) {
def.done(function(response) {
$('#left').append(response);
serialize();
});
}
}());
}
/* METHOD 2 */
var j, responseArr = ['0','0','0','0','0','0','0','0','0','0'];
for (j = 0; j < 10; j++) {
$.ajax({
url: '/echo/html/',
data: {
html: '<h2>Right response number ' + j + '</h2>',
delay: Math.floor(Math.random() * 4 + 1)
},
type: 'post'
}).done(function(data) {
responseArr[i] = data;
}).fail(function(xhr, status, error) {
responseArr[i] = 'FAIL';
}).always(function(data) {
$.each(responseArr, function(i) {
if (responseArr[i] === '0') {
return;
}
else if (responseArr[i] !== 'done') {
$('#right').append(data);
responseArr[i] = 'done';
}
});
});
}