Programming Tutorials

promise and .then() in JavaScript

By: Willet in Javascript Tutorials on 2023-04-26  

promise

A promise is an object in JavaScript that represents the eventual completion or failure of an asynchronous operation, and its resulting value. It allows you to write asynchronous code in a more synchronous way, making it easier to read and reason about. A promise can be in one of three states:

  1. Pending: The initial state, neither fulfilled nor rejected.
  2. Fulfilled: The operation completed successfully, and the promise has a resulting value.
  3. Rejected: The operation failed, and the promise has a reason for the failure.

Promises have two main methods: then() and catch(). then() is called when the promise is fulfilled, and takes a callback function with the resolved value as an argument. catch() is called when the promise is rejected, and takes a callback function with the reason for the rejection as an argument.

Here's an example of a promise that returns a resolved value:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Success!');
  }, 1000);
});

promise.then((result) => {
  console.log(result); // Output: 'Success!'
});

In this example, the promise resolves after a delay of 1 second, and the then() method is called with the resolved value of 'Success!'.

.then()

In JavaScript, .then() is a method used to handle promises, which are objects representing the eventual completion (or failure) of an asynchronous operation and its resulting value.

The .then() method is used to register a callback function that is called when a promise is resolved, and it takes two arguments: a callback function to be called when the promise is fulfilled (which can also return a promise), and a callback function to be called when the promise is rejected.

Here's an example of how to use .then() with a promise:

const promise = new Promise((resolve, reject) => {
  // Do some asynchronous operation
  setTimeout(() => {
    resolve('Success!');
  }, 1000);
});

promise
  .then((result) => {
    console.log(result); // Output: "Success!"
  })
  .catch((error) => {
    console.error(error); // Output: "An error occurred!"
  });

In the example above, we create a new promise that resolves after a timeout of 1 second, then we use .then() to register a callback function that logs the resolved value to the console. If an error occurred, the .catch() method would be called instead.

We use .then() when we want to handle the result of a promise, which is returned asynchronously, and perform some action once the promise is resolved. It's a powerful tool for working with asynchronous code in JavaScript.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)