Then and catch methods help you handle results and errors when working with tasks that take time, like loading data from the internet.
Then and catch methods in Javascript
Introduction
Syntax
Javascript
promise.then(successFunction).catch(errorFunction);then runs when the task finishes well.
catch runs if there is an error.
Examples
Javascript
fetch('url').then(response => response.json()).catch(error => console.error(error));
Javascript
promise.then(() => console.log('Done!')).catch(() => console.log('Failed!'));
Javascript
new Promise((resolve, reject) => { resolve('Success'); }).then(result => console.log(result));
Sample Program
This program creates a promise that either succeeds or fails. Then it prints a success message or an error message depending on the result.
Javascript
const promise = new Promise((resolve, reject) => { const success = true; if (success) { resolve('Task completed successfully'); } else { reject('Task failed'); } }); promise .then(message => { console.log('Success:', message); }) .catch(error => { console.log('Error:', error); });
Important Notes
You can chain multiple then methods to do steps one after another.
Always use catch to handle errors and avoid your program crashing.
then and catch make your code easier to read than using callbacks.
Summary
Then runs when a task finishes well.
Catch runs when a task fails.
They help manage tasks that take time, like loading data.
Practice
1. What does the
then method do in JavaScript promises?easy
Solution
Step 1: Understand the role of
Thethenthenmethod is used to handle the result when a promise completes successfully.Step 2: Differentiate from
Thecatchcatchmethod handles errors or failures, not success.Final Answer:
Runs when the task finishes successfully -> Option DQuick 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
Solution
Step 1: Recall correct catch syntax
The catch method is called directly on the promise object likep.catch(callback).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.Final Answer:
p.catch(() => console.log('Error')) -> Option CQuick Check:
Usepromise.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
Solution
Step 1: Follow promise resolution
The promise resolves with 'Hello'. The first then adds ' World' to it, resulting in 'Hello World'.Step 2: Output from second then
The second then logs the result 'Hello World'. The catch is not called because no error occurs.Final Answer:
Hello World -> Option BQuick 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
Solution
Step 1: Analyze first chain
The first chain calls then twice and catch last, so errors are caught properly.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.Final Answer:
The second chain logs data even if fetch fails -> Option AQuick 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
Solution
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.Step 2: Place catch at the end
Catch should be last to handle any error from either fetchUser or fetchPosts.Final Answer:
fetchUser().then(user => fetchPosts(user.id)).then(posts => console.log(posts)).catch(err => console.log('Error:', err)); -> Option AQuick 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
10 questions ~5 mineasy hard
