JSFiddle - React, Tailwind, and code Playground
JavaScript
async function main() {
const pageCount = 8;
const pages = Array(pageCount)
.fill(null)
.map((_v, index) => index+1);
console.log(pages)
const startTime = Date.now()
let dodoTime = 0;
// Start all requests without waiting
const pendingRequests = pages
.map(async page => {
const requestStartTime = Date.now();
const request = await fetch(`${location.origin}?page=${page}"`);
dodoTime += Date.now() - requestStartTime;
return request.text()
})
console.log(pendingRequests)
// wait until all of the paralelized requests have finished, including the parsing
await Promise.all(pendingRequests)
for (let index = 0; index < pendingRequests.length; index++) {
// you don't really need to "await", because the promise has already been resolved at this point,
// but you still need to unpack the promise. `await` is still cleaner than using ".then()".
// This action is instantaneous.
const element = await pendingRequests[index];
// DON'T SHOW THE RESPONSE OR ELSE JSFIDDLE CRASHES
console.log(element.length)
}
console.log(`Paralized requests took ${Date.now() - startTime}ms instead of ${dodoTime}ms`);
}
main();