How to Avoid Being Sequential
Case 1
async function series() {
await wait(500); // Wait 500ms…
await wait(500); // …then wait another 500ms.
return "done!";
}
It takes 1000ms to complete.async function parallel() {
const wait1 = wait(500); // Start a 500ms timer asynchronously…
const wait2 = wait(500); // …meaning this timer happens in parallel.
await wait1; // Wait 500ms for the first timer…
await wait2; // …by which time this timer has already finished.
return "done!";
}
It takes 500ms to complete, both “waits” happen at the same time.Case 2
Original Promise Pattern
function logInOrder(urls) {
// fetch all the URLs
const textPromises = urls.map(url => {
return fetch(url).then(response => response.text());
});
// log them in order
textPromises.reduce((chain, textPromise) => {
return chain.then(() => textPromise)
.then(text => console.log(text));
}, Promise.resolve());
}
Modify into Async Function Pattern
👎 Too sequentialasync function logInOrder(urls) {
for (const url of urls) {
const response = await fetch(url);
console.log(await response.text());
}
}
Second fetch doesn’t begin until my first fetch has been fully read, and so on. This is much slower than the promises example that performs the fetches in parallel.👍 Nice and parallel
async function logInOrder(urls) {
// fetch all the URLs in parallel
const textPromises = urls.map(async url => {
const response = await fetch(url);
return response.text();
});
// log them in sequence
for (const textPromise of textPromises) {
console.log(await textPromise);
}
}
The URLs is now fetched and read in parallel.