0
0
Javascriptprogramming~5 mins

Promise error handling in Javascript

Choose your learning style9 modes available
Introduction

Promises help manage tasks that take time, like loading data. Error handling lets you catch problems if something goes wrong.

When fetching data from the internet and you want to handle failures.
When reading files or doing tasks that might fail asynchronously.
When calling APIs and you want to show a message if the call fails.
When chaining multiple tasks and need to catch errors anywhere in the chain.
Syntax
Javascript
promise.then(result => {
  // handle success
}).catch(error => {
  // handle error
});

.then() runs when the task succeeds.

.catch() runs if there is an error.

Examples
This example fetches data from the internet and logs it. If there is an error, it logs the error message.
Javascript
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
This creates a promise that fails and catches the error to print it.
Javascript
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));
Sample Program

This program checks if a number is greater than 10. It prints success or error messages depending on the number.

Javascript
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));
OutputSuccess
Important Notes

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.

Summary

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.