Can you tell me what a promise is?

Experience Level: Junior
Tags: JavaScript

Answer

In JavaScript, a promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. It allows for asynchronous code to be written in a more synchronous style, avoiding callback hell.

A promise can be in one of three states:

  • Pending: The initial state of a promise, before it is resolved or rejected.
  • Resolved: The state of a promise when it has been successfully resolved with a value.
  • Rejected: The state of a promise when it has been rejected with a reason (an error object).

Here's an example of how to create and use a promise in JavaScript:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    const randomNumber = Math.random();
    if (randomNumber >= 0.5) {
      resolve(randomNumber);
    } else {
      reject(new Error('Number is less than 0.5'));
    }
  }, 1000);
});

myPromise.then(result => {
  console.log(result);
}).catch(error => {
  console.error(error);
});

In this example, a promise is created using the Promise constructor, which takes a function as an argument. The function is passed two arguments, resolve and reject, which are functions that are used to either resolve or reject the promise. In this case, a random number is generated and if it is greater than or equal to 0.5, the promise is resolved with the number as its value. Otherwise, the promise is rejected with an error object.

The then() method is used to handle the resolved value of the promise, and the catch() method is used to handle any errors that may occur during the asynchronous operation.

Comments

No Comments Yet.
Be the first to tell us what you think.