Bird
Raised Fist0
Javascriptprogramming~10 mins

Error handling with async and await in Javascript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Error handling with async and await
Start async function
↓
Try block: await async call
↓
Async call success?
No→Catch block: handle error
↓
Error handled/logged
↓
Continue after await
↓
End function
The async function tries to await a promise. If it succeeds, it continues. If it fails, the catch block handles the error.
Execution Sample
Javascript
async function fetchData() {
  try {
    const response = await fetch('url');
    console.log('Data received');
  } catch (error) {
    console.log('Error:', error.message);
  }
}
This code tries to fetch data asynchronously and logs success or error message.
Execution Table
StepActionEvaluationResult
1Call fetchData()Start async functionWaiting for fetch()
2Await fetch('url')fetch promise pendingWaiting for response
3fetch resolves successfullyTry block continuesData received logged
4Function endsNo errorNormal completion
5Call fetchData() againStart async functionWaiting for fetch()
6Await fetch('url')fetch promise rejectedError thrown
7Catch block runsError caughtError message logged
8Function endsHandled errorNormal completion
💡 Execution stops after function completes normally or after error is caught and handled.
Variable Tracker
VariableStartAfter Step 3After Step 7Final
responseundefinedResponse objectundefinedundefined
errorundefinedundefinedError objectError object
Key Moments - 3 Insights
Why does the catch block run only when fetch fails?
Because in the execution_table at step 6, the fetch promise rejects, triggering the catch block at step 7 to handle the error.
What happens to the variable 'response' if fetch fails?
As shown in variable_tracker, 'response' remains undefined after step 7 because the assignment in the try block never completes.
Does the function stop immediately when an error occurs?
No, the function continues to the catch block to handle the error, then ends normally as seen in steps 7 and 8.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is logged at step 3?
A'Data received'
B'Error: ...'
CNothing logged
D'Waiting for fetch()'
💡 Hint
Check the 'Result' column at step 3 in execution_table.
At which step does the catch block handle an error?
AStep 4
BStep 2
CStep 7
DStep 1
💡 Hint
Look for 'Catch block runs' in the 'Action' column of execution_table.
If fetch never fails, what happens to the 'error' variable?
AIt becomes an Error object
BIt remains undefined
CIt stores the response data
DIt causes the function to crash
💡 Hint
See variable_tracker for 'error' after step 3 when fetch succeeds.
Concept Snapshot
async function example() {
  try {
    const result = await promise;
    // success path
  } catch (err) {
    // error handling
  }
}
Use try-catch to handle errors from awaited promises safely.
Full Transcript
This visual trace shows how an async function uses try-catch to handle errors. The function starts and awaits a fetch call. If fetch succeeds, the try block logs success and the function ends normally. If fetch fails, the error is caught in the catch block and logged, then the function ends normally. Variables 'response' and 'error' change accordingly. This pattern helps keep async code safe and clear.

Practice

(1/5)
1. What is the main purpose of using try...catch with async and await in JavaScript?
easy
A. To handle errors that occur during asynchronous operations
B. To make the code run faster
C. To convert asynchronous code into synchronous code
D. To declare variables inside async functions

Solution

  1. Step 1: Understand async/await behavior

    Async functions return promises, and await pauses execution until the promise settles.
  2. Step 2: Role of try...catch with async/await

    Errors in awaited promises can be caught using try...catch to prevent program crashes.
  3. Final Answer:

    To handle errors that occur during asynchronous operations -> Option A
  4. Quick Check:

    Error handling = To handle errors that occur during asynchronous operations [OK]
Hint: Use try...catch around await to catch async errors [OK]
Common Mistakes:
  • Thinking async/await makes code synchronous
  • Ignoring errors from awaited promises
  • Using try...catch without async functions
2. Which of the following is the correct syntax to catch errors from an async function using await?
easy
A. try await asyncFunc() catch error { console.log(error); }
B. await try { asyncFunc(); } catch (error) { console.log(error); }
C. asyncFunc().catch(error => console.log(error));
D. try { await asyncFunc(); } catch (error) { console.log(error); }

Solution

  1. Step 1: Identify correct try...catch syntax

    try...catch blocks wrap code that might throw errors; await must be inside try.
  2. Step 2: Check each option's syntax

    try { await asyncFunc(); } catch (error) { console.log(error); } correctly wraps await in try and catches errors; others have syntax errors or misuse await.
  3. Final Answer:

    try { await asyncFunc(); } catch (error) { console.log(error); } -> Option D
  4. Quick Check:

    Correct try...catch with await = try { await asyncFunc(); } catch (error) { console.log(error); } [OK]
Hint: Put await inside try block to catch errors [OK]
Common Mistakes:
  • Placing await outside try block
  • Using incorrect try...catch syntax
  • Confusing promise.catch with try...catch
3. What will be the output of the following code?
async function fetchData() {
  try {
    let result = await Promise.reject('Failed');
    console.log('Success:', result);
  } catch (error) {
    console.log('Error:', error);
  }
}
fetchData();
medium
A. Success: Failed
B. Error: Failed
C. Uncaught (in promise) Failed
D. No output

Solution

  1. Step 1: Analyze Promise.reject inside try block

    Promise.reject('Failed') creates a rejected promise; await pauses until rejection.
  2. Step 2: Catch block handles the rejection error

    The rejection triggers catch block, printing 'Error: Failed'.
  3. Final Answer:

    Error: Failed -> Option B
  4. Quick Check:

    Rejected promise caught = Error: Failed [OK]
Hint: Rejected promises inside try trigger catch block [OK]
Common Mistakes:
  • Expecting success message on rejection
  • Missing catch block causes unhandled rejection
  • Confusing Promise.reject with Promise.resolve
4. Identify the error in this code snippet:
async function load() {
  try {
    const data = await fetch('https://api.example.com/data');
  } catch {
    console.log('Fetch failed');
  }
}
load();
medium
A. Missing error parameter in catch block
B. fetch cannot be awaited
C. async keyword is missing
D. try block cannot contain await

Solution

  1. Step 1: Check catch block syntax

    Catch block should have an error parameter to receive the error object.
  2. Step 2: Confirm other parts are correct

    fetch returns a promise and can be awaited; async keyword is present; try can contain await.
  3. Final Answer:

    Missing error parameter in catch block -> Option A
  4. Quick Check:

    Catch needs error parameter = Missing error parameter in catch block [OK]
Hint: Always include error parameter in catch(e) [OK]
Common Mistakes:
  • Omitting error parameter in catch
  • Thinking fetch is synchronous
  • Removing async keyword by mistake
5. You want to fetch user data and then fetch posts for that user. If either fetch fails, you want to log the error and continue without stopping the program. Which code correctly handles errors using async/await?
hard
A. async function getUserAndPosts() { try { const user = await fetch('/user'); const posts = await fetch(`/posts?userId=${user.id}`); } catch (e) { console.log('Error:', e); } }
B. async function getUserAndPosts() { const user = await fetch('/user').catch(e => console.log('User fetch error:', e)); const posts = await fetch(`/posts?userId=${user.id}`).catch(e => console.log('Posts fetch error:', e)); }
C. async function getUserAndPosts() { try { const user = await fetch('/user'); } catch (e) { console.log('User fetch error:', e); } try { const posts = await fetch(`/posts?userId=${user.id}`); } catch (e) { console.log('Posts fetch error:', e); } }
D. async function getUserAndPosts() { const user = fetch('/user'); const posts = fetch(`/posts?userId=${user.id}`); console.log('Data fetched'); }

Solution

  1. Step 1: Understand error handling for multiple awaits

    Separate try...catch blocks allow handling errors individually without stopping the whole function.
  2. Step 2: Analyze each option

    async function getUserAndPosts() { try { const user = await fetch('/user'); } catch (e) { console.log('User fetch error:', e); } try { const posts = await fetch(`/posts?userId=${user.id}`); } catch (e) { console.log('Posts fetch error:', e); } } uses separate try...catch for user and posts fetch, logging errors and continuing execution. async function getUserAndPosts() { try { const user = await fetch('/user'); const posts = await fetch(`/posts?userId=${user.id}`); } catch (e) { console.log('Error:', e); } } stops on first error. async function getUserAndPosts() { const user = await fetch('/user').catch(e => console.log('User fetch error:', e)); const posts = await fetch(`/posts?userId=${user.id}`).catch(e => console.log('Posts fetch error:', e)); } mixes await with .catch but can cause undefined user. async function getUserAndPosts() { const user = fetch('/user'); const posts = fetch(`/posts?userId=${user.id}`); console.log('Data fetched'); } lacks await and error handling.
  3. Final Answer:

    Option C correctly handles errors separately and continues execution -> Option C
  4. Quick Check:

    Separate try...catch for each await = async function getUserAndPosts() { try { const user = await fetch('/user'); } catch (e) { console.log('User fetch error:', e); } try { const posts = await fetch(`/posts?userId=${user.id}`); } catch (e) { console.log('Posts fetch error:', e); } } [OK]
Hint: Use separate try...catch blocks to handle multiple awaits safely [OK]
Common Mistakes:
  • Using one try...catch for multiple awaits stopping on first error
  • Mixing await with .catch causing undefined variables
  • Not awaiting fetch calls
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard