Promise.all(): Concurrent Asynchronous Operations
So far, we've sequenced asynchronous tasks one after another. But when tasks are independent, you can run them in parallel with Promise.all(), which “fail-fast” rejects if any input Promise rejects, or resolves with an array of all results.
1. What is Promise.all()?
Promise.all() takes an array of Promises and returns a new Promise that:
- Resolves when all input Promises resolve, with an array of their values.
- Rejects immediately when any input Promise rejects, with that first rejection reason.
2. Fail-Fast Rejection Behavior
If any Promise rejects, Promise.all() immediately rejects with that error.
3. Using Promise.all() with async/await
You can await a Promise.all() inside an async function to run tasks in parallel and then destructure their results.
Exercise: Fetch Multiple Pokémon Concurrently
Instructions:
- Write an
asyncfunctionfetchPokemonData(). - Define an array of names (e.g.
'pikachu','charizard','squirtle','invalid'). - Map names to Promises via
fetch('https://pokeapi.co/api/v2/pokemon/'+name)+.json(), checkingresponse.ok. await Promise.all()on that array.- On success, log each Pokémon’s
nameandheight. - Use
try...catchto handle any fetch or JSON errors. - Include a
finallyto signal completion.
التالي · الدرس 53 من 61
import / export syntax
قراءة 4 دقيقة
أنهيت 52 من 61 درسًا

اسأل Byte عن هذا الدرس
محادثة خاصة حول هذا الدرس. قرأ Byte الدرس كاملًا، ويجيب خلال ثوانٍ، ويُظهر القسم الذي تأتي منه كل إجابة. يمكنك السؤال بأي لغة.
الأسئلة والأجوبة
أسئلة عامة حول هذا الدرس. يجيب AI Tutor فورًا بلغتك، ويراجع فريق FreeAcademy الإجابات، ويمكن لكل المتعلمين قراءتها.

