Promises and async/await
Some work takes time: downloading data, reading a file, waiting for a timer. JavaScript does not stop and wait. Instead it gives you a promise: an object that will hold the result later.
const later = new Promise(resolve => {
setTimeout(() => resolve("done!"), 1000); // after 1 second
});
later.then(value => console.log(value)); // done! (one second later)
async and await
await pauses inside an async function until a promise settles, so asynchronous code reads like normal code:
async function showWeather(getWeather) {
const weather = await getWeather("Harare"); // waits here
console.log(`It is ${weather.temp} degrees`);
}
An async function always returns a promise. If an awaited promise rejects (fails), await throws, so you can use try/catch.
Many at once: Promise.all
Awaiting one request after another in a loop is slow. Start them all, then wait for all of them together:
const results = await Promise.all([fetchA(), fetchB(), fetchC()]);
Promise.all resolves to an array of results in the same order as the promises you gave it.
Your task
delay(ms): return a promise that resolves aftermsmilliseconds.async getNames(ids, fetchUser):fetchUser(id)returns a promise of{ id, name }. Fetch every id at the same time and return the names, in the same order asids.async firstName(id, fetchUser): return the user's name, or"unknown"if the request fails.