JavaScript Promises

JavaScript Promises

In JavaScript, a promise is an object that represents the eventual completion or failure of an asynchronous operation. Promises provide a simpler alternative for executing, composing, and managing asynchronous operations when compared to callback-based approaches.

A promise can be in one of three states: fulfilled, rejected, or pending. Promises start in the pending state and can either be resolved with a value (fulfilled) or rejected with a reason (error). Once a promise is fulfilled or rejected, it is settled and can no longer transition to a different state.

Promises are used to handle asynchronous operations in JavaScript, such as making HTTP requests or reading from a file. Instead of using callbacks to handle the results of these operations, you can use a promise to represent the operation and its result.

Here's an example of using a promise to make an HTTP request:

const getData = () => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://example.com/data');
    xhr.onload = () => resolve(xhr.responseText);
    xhr.onerror = () => reject(xhr.statusText);
    xhr.send();
  });
};

To use this promise, you would call getData() and use the then() method to specify what should happen when the promise is fulfilled or rejected.

getData()
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

The then() method returns a new promise that is fulfilled with the value returned from the handler function.


  • Date: