Async Functions and Await: Modern Asynchronous JavaScript
While Promises (with .then(), .catch(), .finally()) improve on callback hell, ES2017 introduced async functions and the await keyword to make asynchronous code look synchronous and far more readable.
1. Understanding async Functions
An async function always returns a Promise. Inside it you can use await to pause execution until another Promise settles.
2. The await Keyword
You can only use await inside an async function. It pauses until the awaited Promise settles, throwing an error if the Promise rejects.
3. Error Handling with try...catch
async/await lets you use normal try...catch around multiple awaits, which is far cleaner than chaining .catch() on each Promise.
4. Chaining Promises vs. async/await
| Feature | Promise Chaining | async/await |
|---|---|---|
| Readability | .then().then() can grow verbose | Looks like regular synchronous code |
| Error Handling | .catch() at end or per chain | Use try...catch |
| Flow Control | Explicitly returns Promises | Execution pauses at each await |
Exercise: Refactor Fetch Chain to async/await
Instructions: Refactor the original fetch-and-comments Promise chain into a single async function using await, with proper try...catch and status checks.
التالي · الدرس 51 من 61
Error handling with try/catch
قراءة 5 دقيقة
أنهيت 50 من 61 درسًا

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

