Introduction
Promises help manage tasks that take time, like loading data. Error handling lets you catch problems if something goes wrong.
Promises help manage tasks that take time, like loading data. Error handling lets you catch problems if something goes wrong.
promise.then(result => {
// handle success
}).catch(error => {
// handle error
});.then() runs when the task succeeds.
.catch() runs if there is an error.
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
new Promise((resolve, reject) => { const success = false; if (success) { resolve('Task done'); } else { reject('Task failed'); } }) .then(message => console.log(message)) .catch(error => console.log(error));
This program checks if a number is greater than 10. It prints success or error messages depending on the number.
function checkNumber(num) { return new Promise((resolve, reject) => { if (num > 10) { resolve('Number is greater than 10'); } else { reject('Number is too small'); } }); } checkNumber(15) .then(message => console.log('Success:', message)) .catch(error => console.log('Error:', error)); checkNumber(5) .then(message => console.log('Success:', message)) .catch(error => console.log('Error:', error));
You can use .catch() at the end of a promise chain to catch any error from previous steps.
Always handle errors to avoid your program crashing silently.
Promises let you run code that takes time and handle success or failure.
Use .then() for success and .catch() for errors.
Handling errors helps keep your program working smoothly.
.catch() method when working with JavaScript Promises?.catch() in Promises.catch() method is designed to handle errors or rejected promises in asynchronous code..then() handles successful resolution, while .catch() specifically catches errors..catch() handles errors [OK]myPromise?.catch().myPromise.catch(error => console.log(error)); correctly attaches an error handler.const p = new Promise((resolve, reject) => {
reject('Failed');
});
p.then(result => console.log('Success:', result))
.catch(error => console.log('Error:', error));.then() is skipped because the promise is rejected; .catch() runs and logs 'Error: Failed'.fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log('Error:', error));
// What is wrong here?.then() to parse JSON and then log data..catch() properly handles any errors from fetch or JSON parsing.fetch('https://api.example.com/data')
.then(response => response.json())
.catch(error => {
console.log('Error:', error);
return {};
})
.then(data => console.log('Data:', data));.catch() catches any errors from the fetch or JSON parsing.{} allows the next .then() to receive a value and continue processing.Pass the test and this pattern moves unknown