JSFiddle - React, Tailwind, and code Playground
JavaScript
async function first() {
return new Promise(resolve => setTimeout(() => resolve(1), 100));
}
async function second() {
return new Promise(resolve => setTimeout(() => resolve(1), 200));
}
async function third() {
return new Promise(resolve => setTimeout(() => resolve(1), 300));
}
async function main() {
// If you put await before each call, it will
// sequentially execute them
let timeBefore = Date.now();
let one = await first();
let two = await second();
let three = await third();
let timeAfter = Date.now();
// Should display "600ms"
console.log((timeAfter - timeBefore) + "ms");
// "one", "two", "three" will contain
// the promises we will give to Promise.all
one = first();
two = second();
three = third();
timeBefore = Date.now();
// "results" will be an array containing the
// returning async'ed values of the promises
let results = await Promise.all([one, two, three]);
timeAfter = Date.now();
// Should display "300ms"
console.log((timeAfter - timeBefore) + "ms");
}
main();