Bird
Raised Fist0
Javascriptprogramming~10 mins

Then and catch methods in Javascript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Then and catch methods
Start Promise
↓
Promise Pending
↓
Promise Resolved?
No→Promise Rejected?
↓
Then callback
↓
Continue chain
↓
End
A promise starts pending, then either resolves or rejects. If resolved, the then() callback runs. If rejected, the catch() callback runs.
Execution Sample
Javascript
new Promise((res, rej) => res('Done'))
  .then(result => console.log(result))
  .catch(error => console.log(error));
This code creates a promise that resolves immediately and logs the result using then(), skipping catch().
Execution Table
StepPromise StateActionCallback CalledOutput
1PendingPromise createdNoneNone
2ResolvedResolve called with 'Done'NoneNone
3Resolvedthen() callback runsthenLogs: Done
4ResolvedNo error, catch() skippedNoneNone
5EndPromise chain completeNoneNone
💡 Promise resolved, then() ran, catch() skipped because no error
Variable Tracker
VariableStartAfter Step 2After Step 3Final
promiseStatePendingResolvedResolvedResolved
resultundefined'Done''Done''Done'
errorundefinedundefinedundefinedundefined
Key Moments - 2 Insights
Why does the catch() method not run in this example?
Because the promise resolved successfully (see Step 2 and 3 in execution_table), so then() runs and catch() is skipped.
What happens if the promise rejects instead of resolves?
If the promise rejects, then() is skipped and catch() runs to handle the error (not shown here but implied by the flow).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does the then() callback run?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Check the 'Callback Called' column in execution_table for when then() runs.
According to variable_tracker, what is the value of 'error' after Step 3?
Anull
B'Done'
Cundefined
DAn error object
💡 Hint
Look at the 'error' row and the 'After Step 3' column in variable_tracker.
If the promise rejected at Step 2, which callback would run next?
Athen() callback
Bcatch() callback
CNeither then() nor catch()
DBoth then() and catch()
💡 Hint
Refer to the concept_flow diagram showing promise rejection leads to catch() callback.
Concept Snapshot
Promise.then() runs when promise resolves successfully.
Promise.catch() runs when promise rejects with error.
They help handle asynchronous success and failure.
Use then() to process results, catch() to handle errors.
They chain to manage async flow cleanly.
Full Transcript
This visual trace shows how JavaScript promises work with then() and catch() methods. A promise starts pending, then either resolves or rejects. When it resolves, the then() callback runs to handle the result. If it rejects, the catch() callback runs to handle the error. The example code creates a promise that resolves immediately with 'Done'. The execution table shows the promise state changes and which callbacks run step-by-step. The variable tracker shows how the promise state and result variables change. Key moments clarify why catch() does not run here and what would happen if the promise rejected. The quiz questions test understanding of when callbacks run and variable values during execution. This helps beginners see the flow of asynchronous code handling with promises.

Practice

(1/5)
1. What does the then method do in JavaScript promises?
easy
A. Creates a new promise
B. Runs when the task fails
C. Stops the promise from running
D. Runs when the task finishes successfully

Solution

  1. Step 1: Understand the role of then

    The then method is used to handle the result when a promise completes successfully.
  2. Step 2: Differentiate from catch

    The catch method handles errors or failures, not success.
  3. Final Answer:

    Runs when the task finishes successfully -> Option D
  4. Quick Check:

    then = success handler [OK]
Hint: Remember: then = success, catch = failure [OK]
Common Mistakes:
  • Confusing then with catch
  • Thinking then stops the promise
  • Believing then creates a new promise
2. Which of the following is the correct syntax to add a catch handler to a promise named p?
easy
A. catch(p, () => console.log('Error'))
B. p.then.catch(() => console.log('Error'))
C. p.catch(() => console.log('Error'))
D. p.catch = () => console.log('Error')

Solution

  1. Step 1: Recall correct catch syntax

    The catch method is called directly on the promise object like p.catch(callback).
  2. Step 2: Check each option

    p.catch(() => console.log('Error')) uses correct syntax. p.then.catch(() => console.log('Error')) chains incorrectly. p.catch = () => console.log('Error') tries to assign catch as a property. catch(p, () => console.log('Error')) uses invalid function call.
  3. Final Answer:

    p.catch(() => console.log('Error')) -> Option C
  4. Quick Check:

    Use promise.catch() syntax [OK]
Hint: Use promise.catch(callback) to handle errors [OK]
Common Mistakes:
  • Chaining catch after then incorrectly
  • Assigning catch as a property
  • Using catch as a standalone function
3. What will be the output of this code?
Promise.resolve('Hello')
  .then(msg => msg + ' World')
  .then(console.log)
  .catch(() => console.log('Error'));
medium
A. Hello
B. Hello World
C. Error
D. undefined

Solution

  1. Step 1: Follow promise resolution

    The promise resolves with 'Hello'. The first then adds ' World' to it, resulting in 'Hello World'.
  2. Step 2: Output from second then

    The second then logs the result 'Hello World'. The catch is not called because no error occurs.
  3. Final Answer:

    Hello World -> Option B
  4. Quick Check:

    Promise resolves + then chains = 'Hello World' [OK]
Hint: then chains transform and pass values forward [OK]
Common Mistakes:
  • Expecting catch to run without error
  • Ignoring value returned by first then
  • Thinking console.log returns undefined
4. Identify the error in this code snippet:
fetch('url')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log('Error:', error));

fetch('url')
  .then(response => response.json())
  .catch(error => console.log('Error:', error))
  .then(data => console.log(data));
medium
A. The second chain logs data even if fetch fails
B. The first chain has wrong catch placement
C. Both chains are correct
D. fetch cannot be chained with then and catch

Solution

  1. Step 1: Analyze first chain

    The first chain calls then twice and catch last, so errors are caught properly.
  2. Step 2: Analyze second chain

    The second chain calls catch before the last then. So even if fetch fails, the last then runs with undefined data, causing possible issues.
  3. Final Answer:

    The second chain logs data even if fetch fails -> Option A
  4. Quick Check:

    Catch before then can cause unexpected data [OK]
Hint: Place catch last to handle errors before then [OK]
Common Mistakes:
  • Placing catch before then incorrectly
  • Assuming catch stops later then calls
  • Ignoring promise chain order
5. You want to fetch user data and then fetch their posts only if the user fetch succeeds. Which code correctly uses then and catch to do this?
hard
A. fetchUser() .then(user => fetchPosts(user.id)) .then(posts => console.log(posts)) .catch(err => console.log('Error:', err));
B. fetchUser() .catch(err => console.log('Error:', err)) .then(user => fetchPosts(user.id)) .then(posts => console.log(posts));
C. fetchUser() .then(user => fetchPosts(user.id)) .catch(err => console.log('Error:', err)) .then(posts => console.log(posts));
D. fetchUser() .then(user => fetchPosts(user.id)) .catch(err => console.log('Error:', err)) .catch(err => console.log('Another error:', err));

Solution

  1. Step 1: Understand chaining for dependent tasks

    We want to fetch posts only if user fetch succeeds, so fetchPosts must be inside the first then.
  2. Step 2: Place catch at the end

    Catch should be last to handle any error from either fetchUser or fetchPosts.
  3. Final Answer:

    fetchUser().then(user => fetchPosts(user.id)).then(posts => console.log(posts)).catch(err => console.log('Error:', err)); -> Option A
  4. Quick Check:

    Chain then for success, catch last for errors [OK]
Hint: Chain dependent tasks in then, catch errors last [OK]
Common Mistakes:
  • Placing catch before all then calls
  • Calling then after catch causing unexpected runs
  • Using multiple catch handlers unnecessarily
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