JSFiddle - React, Tailwind, and code Playground
by jfriend00
HTML
<div id="progress">Calling multiple Ajax calls - will take 10 seconds...</div>
CSS
body {
font-family: "Courier New";
}
JavaScript
function requestPages(startPage, endPage) {
function request(page, items){
// building the AJAX return value for
// JSFiddle dummy AJAX endpoint
var ret = {
currentPage: page,
items: []
};
for (var i = page; i < (page + 5); i++){
ret.items.push(i);
}
// Do Ajax call, return its promise
return $.ajax({
url: '/echo/json/',
method: 'POST',
dataType: 'json',
data: {
delay: 1,
json: JSON.stringify(ret)
}
}).then(function(data) {
// mock filter here to give us just odd values
var filtered = data.items.filter(function(el){
return el % 2 == 1;
});
// add these items to the ones we have so far
items = items.concat(filtered);
// if we have more pages to go, then do the next one
if (page < endPage){
// Advance the currentPage, call function to process it and
// return a new promise that will be chained back to the
// promise that was originally returned by requestPages()
return request(page + 1, items);
} else {
// Finish our iteration and
// return the accumulated items.
// This will propagate back through
// all the other promises to the original promise
// that requestPages() returned
return(items);
}
});
}
// call the first request and return it's promise
return request(startPage, []);
}
requestPages(1, 10).done(function(items) {
// all ajax calls are done
log(items);
$("#progress").html("Ajax calls done");
});
function log(args) {
var str = "";
for (var i = 0; i < arguments.length; i++) {
if (typeof...