What are JavaScript promises? How do they work?

JavaScript promises are objects used for handling asynchronous operations. They represent the eventual completion (or failure) of an asynchronous operation and allow you to write more readable and maintainable asynchronous code.

Promises work based on the concept of “callbacks.” Traditionally, callbacks were used to handle asynchronous operations, but they can result in callback hell and make the code difficult to read and manage, especially when dealing with multiple asynchronous tasks.

Promises provide a more structured and organized way to handle asynchronous operations. They have three states:

Pending: The initial state when the Promise is created, and the asynchronous operation is still in progress.

Fulfilled: The state when the asynchronous operation is successfully completed, and the Promise is resolved with a value.

Rejected: The state when the asynchronous operation encounters an error or failure, and the Promise is rejected with a reason or error message.

Here’s an example that demonstrates the basic usage of promises:

function fetchData() {

  return new Promise((resolve, reject) => {

    setTimeout(() => {

      const data = ‘Data fetched successfully’;

      // Simulating a successful asynchronous operation

      resolve(data); // Resolve the Promise with the data

      // Uncomment the following line to simulate a failure

      // reject(‘Error occurred’); // Reject the Promise with an error message

    }, 2000);

  });

}

// Using the Promise

fetchData()

  .then((data) => {

    console.log(‘Success:’, data);

  })

  .catch((error) => {

    console.log(‘Error:’, error);

  });

In the example above, the fetchData function returns a Promise. Inside the Promise’s executor function, an asynchronous operation (simulated by a setTimeout with a 2-second delay) is performed. If the operation is successful, the Promise is resolved using the `resolve’ method with the data as the resolved value. If an error occurs, the Promise is rejected using the reject function with an error message.

The Promise returned by fetchData can be consumed using the then method, which takes two callbacks as arguments: one for handling the fulfillment (resolved state) and another for handling the rejection (rejected state). In the example, the then method is used to handle the fulfillment and the catch method to handle the rejection.

When the Promise is fulfilled, the success callback is executed, and the resolved value (data) is passed as an argument. In case of rejection, the error callback is executed, and the reason for rejection (error) is passed as an argument.

Promises also support chaining, allowing you to perform multiple asynchronous operations sequentially. The then method returns a new Promise, so you can chain additional then or catch methods to handle subsequent operations.

What are JavaScript promises? How do they work?

JavaScript promises are objects used for handling asynchronous operations. They represent the eventual completion (or failure) of an asynchronous operation and allow you to write more readable and maintainable asynchronous code.

Promises work based on the concept of “callbacks.” Traditionally, callbacks were used to handle asynchronous operations, but they can result in callback hell and make the code difficult to read and manage, especially when dealing with multiple asynchronous tasks.

Promises provide a more structured and organized way to handle asynchronous operations. They have three states:

Pending: The initial state when the Promise is created, and the asynchronous operation is still in progress.

Fulfilled: The state when the asynchronous operation is successfully completed, and the Promise is resolved with a value.

Rejected: The state when the asynchronous operation encounters an error or failure, and the Promise is rejected with a reason or error message.

Here’s an example that demonstrates the basic usage of promises:

function fetchData() {

  return new Promise((resolve, reject) => {

    setTimeout(() => {

      const data = ‘Data fetched successfully’;

      // Simulating a successful asynchronous operation

      resolve(data); // Resolve the Promise with the data

      // Uncomment the following line to simulate a failure

      // reject(‘Error occurred’); // Reject the Promise with an error message

    }, 2000);

  });

}

// Using the Promise

fetchData()

  .then((data) => {

    console.log(‘Success:’, data);

  })

  .catch((error) => {

    console.log(‘Error:’, error);

  });

In the example above, the fetchData function returns a Promise. Inside the Promise’s executor function, an asynchronous operation (simulated by a setTimeout with a 2-second delay) is performed. If the operation is successful, the Promise is resolved using the `resolve’ method with the data as the resolved value. If an error occurs, the Promise is rejected using the reject function with an error message.

The Promise returned by fetchData can be consumed using the then method, which takes two callbacks as arguments: one for handling the fulfillment (resolved state) and another for handling the rejection (rejected state). In the example, the then method is used to handle the fulfillment and the catch method to handle the rejection.

When the Promise is fulfilled, the success callback is executed, and the resolved value (data) is passed as an argument. In case of rejection, the error callback is executed, and the reason for rejection (error) is passed as an argument.

Promises also support chaining, allowing you to perform multiple asynchronous operations sequentially. The then method returns a new Promise, so you can chain additional then or catch methods to handle subsequent operations.