0
0
Javascriptprogramming~5 mins

Then and catch methods in Javascript

Choose your learning style9 modes available
Introduction

Then and catch methods help you handle results and errors when working with tasks that take time, like loading data from the internet.

When you want to do something after a task finishes successfully.
When you want to handle errors if a task fails.
When working with promises to manage asynchronous actions.
When loading data from a server and you want to process it or show an error.
When chaining multiple steps that depend on each other.
Syntax
Javascript
promise.then(successFunction).catch(errorFunction);

then runs when the task finishes well.

catch runs if there is an error.

Examples
Get data from a URL, convert it to JSON if successful, or show an error if it fails.
Javascript
fetch('url').then(response => response.json()).catch(error => console.error(error));
Print messages depending on success or failure of the promise.
Javascript
promise.then(() => console.log('Done!')).catch(() => console.log('Failed!'));
Create a promise that always succeeds and print the result.
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);
  });
OutputSuccess
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.