What if you could handle waiting and errors in your code as easily as ordering food online?
Why Then and catch methods in Javascript? - Purpose & Use Cases
Imagine you want to get data from the internet and then show it on your webpage. Without special tools, you have to wait and check again and again if the data is ready. This waiting and checking by hand can be confusing and messy.
Doing this waiting manually means writing lots of code that is hard to read and easy to break. If something goes wrong, you might miss the error or your program might stop working without telling you why. It's like trying to catch a ball while blindfolded.
The then and catch methods let you say: "When the data is ready, do this" and "If there is an error, do that." This makes your code clean, easy to follow, and safe from unexpected problems.
fetchData(function(data) {
processData(data);
}, function(error) {
handleError(error);
});fetchData() .then(data => processData(data)) .catch(error => handleError(error));
It lets you write smooth, clear steps for handling tasks that take time, making your programs more reliable and easier to understand.
Think of ordering food online: you place an order, then wait for confirmation (then), or get a message if the restaurant is closed (catch). This keeps you informed without guessing.
Manual waiting for tasks is slow and confusing.
Then and catch make handling success and errors simple.
This approach keeps your code clean and your app reliable.
Practice
then method do in JavaScript promises?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]
- Confusing then with catch
- Thinking then stops the promise
- Believing then creates a new promise
p?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]
- Chaining catch after then incorrectly
- Assigning catch as a property
- Using catch as a standalone function
Promise.resolve('Hello')
.then(msg => msg + ' World')
.then(console.log)
.catch(() => console.log('Error'));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]
- Expecting catch to run without error
- Ignoring value returned by first then
- Thinking console.log returns undefined
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));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]
- Placing catch before then incorrectly
- Assuming catch stops later then calls
- Ignoring promise chain order
then and catch to do this?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]
- Placing catch before all then calls
- Calling then after catch causing unexpected runs
- Using multiple catch handlers unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
