Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

explain promise with example in javascript

In JavaScript, a Promise is an object representing the eventual completion or failure of an asynchronous operation, and its resulting value. Promises can be used to handle asynchronous code in a more synchronous manner, allowing for better error handling and code readability.

Here is an example of using a Promise to asynchronously fetch data from an API:

const fetchData = new Promise((resolve, reject) => {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => resolve(data))
    .catch(error => reject(error));
});

fetchData.then(data => console.log(data)).catch(error => console.error(error));
Enter fullscreen mode Exit fullscreen mode

In this example, a Promise is created using the new Promise() constructor. The Promise takes in a callback function that contains the asynchronous code to be executed. In this case, we use the fetch method to make an HTTP request to the specified API endpoint, parse the response as JSON, and then resolve the Promise with the resulting data using the resolve function. If an error occurs, the Promise is rejected with the error using the reject function.

The Promise is then used by chaining the .then() method to handle the resolved value, and the .catch() method to handle any errors that may occur during the execution of the Promise. In this example, we log the resulting data to the console if the Promise is resolved, or log the error to the console if the Promise is rejected.

Promises can be especially useful when dealing with multiple asynchronous operations in a sequence, as they allow for cleaner and more readable code.

Image description

Image description
OUTPUT

Image description

OUTPUT

Image description
OUTPUT

Image description

Image description

OUTPUT
Image description

====================================================

Image description

Image description

OUTPUT

Image description

Image description
OUTPUT

Image description

Image description

=======================================================

Image description
OUTPUT

Image description

Image description

OUTPUT

Image description

Image description

Top comments (0)