OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 25

Async / Await Syntax and Error Handling

By Ratan Updated: 16 Oct 2026

Write clean synchronous-looking asynchronous code using ES8 async and await keywords.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Write promise-based flow in sequential steps

An async function always returns a promise. await pauses that function's continuation until the awaited value settles; it does not block the whole browser or make synchronous CPU work run on another thread.

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function prepareLesson() {
  await delay(50);
  return { title: 'Promises', ready: true };
}
async function showLesson() {
  try {
    const lesson = await prepareLesson();
    console.log(lesson.title); // Promises
  } catch (error) {
    console.error('Preparation failed:', error.message);
  } finally {
    console.log('Preparation attempt finished');
  }
}
showLesson();

Catch the awaited rejection

A rejected awaited promise throws at the await point, so try/catch can handle it. Calling an async function without awaiting or otherwise handling its promise can leave a rejection unhandled. If a catch cannot recover, add context and rethrow rather than returning an indistinguishable success value.

Sequential versus parallel

const [left, right] = await Promise.all([
  loadLeft(),
  loadRight()
]);

This fragment belongs inside an async context and assumes both functions exist. Use it when requests are independent. If the second request needs the first request's result, sequential awaits express that dependency. Promise.all's rejection does not cancel the other request automatically.

Cleanup can change control flow

finally runs after try/catch, but a return or throw inside finally can override an earlier outcome. Keep it focused on cleanup. A pending-state button should be re-enabled there, while the success/error message belongs to the corresponding result path.

Practice

  1. Make prepareLesson throw and confirm the catch path.
  2. Compare two independent delays awaited sequentially versus Promise.all.
  3. Explain why const x = prepareLesson() is a promise rather than the lesson object.
  4. Use for...of with await for intentionally sequential work; do not assume forEach awaits async callbacks.

हिन्दी संकेत: await केवल async function का आगे का काम रोकता है, browser की पूरी execution नहीं।

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat