javascript · level 3 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
waits for many promises at the same time.
Awaiting three requests one by one is : each waits for the last, so the waits add up. Start them all first, then wait for the lot with Promise.all. They run , so the total wait is only as long as the slowest one.
Promise.all takes an array of promises and resolves with an array of their values, in the order you gave them, whichever finishes first. If any one rejects, the whole thing rejects straight away with that error.
const base = "https://api.example.com/users";
async function getName(id) {
const reply = await fetch(`${base}/${id}`);
const user = await reply.json();
return user.name;
}
const names = await Promise.all([1, 2, 3].map(getName));
console.log(names); [1, 2, 3].map(getName) starts all three requests to the practice server at once and gives back an array of promises.
guess first
Slow, fast and medium. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const results = await Promise.all([wait(300, "slow"), wait(100, "fast"), wait(200, "medium")]);
console.log(results);
your turn
Your turn. Price a basket in one go.
The practice server knows the prices of bread, milk, eggs and jam. Pick eggs or jam for the third item, then pass price to map so every request starts at once.
fix it
The stock total crashes. Can you fix it?
- What is
countson line 7: an array of numbers, or something else? Promise.allgives back a promise. A promise has noreducemethod, so it is a TypeError.- Write
awaitbeforePromise.allon line 7, then press run.
nailed it
you can wait for many things at once. :D
- Start promises together;
Promise.allwaits for them in parallel. - Results come back in the order you asked for them.
- One rejection makes the whole
Promise.allreject.
new words in your collection
- sequential
- in parallel
- Promise.all
This lesson isn’t saved. A free account remembers every lesson you finish.