---
title: "What are Promises in JavaScript and how do they work?"  
description: "What are Promises in JavaScript and how do they work?"  
author: "Sandra Emily"  
published: 2024-06-18  
updated: 2024-06-19  
canonical: https://www.mindstick.com/forum/160757/what-are-promises-in-javascript-and-how-do-they-work  
category: "javascript"  
tags: ["web development", "javascript", "front-end development"]  
reading_time: 4 minutes  

---

# What are Promises in JavaScript and how do they work?

What are Promises in JavaScript and how do they work?

## Replies

### Reply by Ravi Vishwakarma

A [promise](https://www.mindstick.com/forum/159913/how-to-handle-the-result-of-a-resolved-promise) is an [asynchronous](https://www.mindstick.com/blog/304336/asynchronous-programming-with-async-await-task-in-c-sharp) action that may be completed at some point in the future and produce a value. This value is not necessarily known at the time of its creation. Once the value is produced, it notifies the user.

[Promises](https://www.mindstick.com/forum/159923/explain-the-role-of-the-promise-resolve-and-promise-reject-methods) provide a robust way to wrap the result of asynchronous work, overcoming the problem of deeply nested callbacks.

The Promise object takes a **callback function** as a parameter, which, in turn, takes **two parameters**, **resolve and reject**. The promise is either fulfilled or **rejected**.

Here's an in-depth look at what Promises are and how they work:

#### Basics of Promise

A promise created using the `promise` constructor in JavaScript.

```javascript
let promise = new Promise((resolve, reject) => {
  // Asynchronous operation here
  if (/* operation is successful */) {
    resolve(result); // Successfully completed
  } else {
    reject(error); // Failed
  }
});
```

## States

A Promise has three states:

- **Pending**: The initial state. The operation is ongoing.
- **Fulfilled**: The operation was completed successfully.
- **Rejected**: The operation failed.

#### Working with Promises

**Chaining** with `.then()`

Once a Promise is **fulfilled** or **rejected**, you can handle the result or error using `.then()` and `.catch()`:

```javascript
promise.then((result) => {
  // Handle the result
}).catch((error) => {
  // Handle the error
});
```

You can add multiple `.then()` methods to handle a sequence of asynchronous operations:

```javascript
promise
  .then((result1) => {
    // Handle the result of the first operation
    return anotherAsyncOperation(result1);
  })
  .then((result2) => {
    // Handle the result of the second operation
  })
  .catch((error) => {
    // Handle any error that occurs in the chain
  });
```

Using `.finally()`

The `.finally()` method is used to execute a callback once the Promise is settled **(fulfilled or rejected):**

```javascript
promise
  .then((result) => {
    // Handle the result
  })
  .catch((error) => {
    // Handle the error
  })
  .finally(() => {
    // Cleanup or final actions
  });
```

## Summary

- **Promises** represent the eventual completion or failure of asynchronous operations.
- They have three states: **pending**, **fulfilled**, and **rejected**.
- Use `.then()` for handling fulfilled results, `.catch()` for handling errors, and `.finally()` for cleanup actions.
- `Promise.all()` and `Promise.race()` help in combining multiple Promises.
- `async` and `await` provide a more synchronous-like way to handle asynchronous code.

#### Example: Fetch Data from an API using Promises

```javascript
// Function to fetch data from an API
function fetchData() {
  // Use the fetch API to get data from the given URL
  fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => {
      // Check if the response status is OK (status code 200)
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      // Parse the JSON from the response
      return response.json();
    })
    .then(data => {
      // Handle the data
      console.log('Data:', data);
    })
    .catch(error => {
      // Handle any errors that occur
      console.error('There was a problem with the fetch operation:', error);
    });
}

// Call the function to fetch data
fetchData();
```

#### Explanation:

1. `fetch('https://jsonplaceholder.typicode.com/posts/1')`**:** Initiates a network request to the specified URL. `fetch` returns a Promise that resolves to the `Response` object representing the response to the request.
2. `.then(response => {...})`**:** The first `.then()` method processes the `Response` object. The `response.ok` property checks if the response status is in the range 200-299, indicating a successful request.
3. `return response.json();`**:** If the response is okay, we call `response.json()` to parse the JSON body text from the response. This returns a Promise that resolves to the parsed JSON data.
4. `.then(data => {...})`**:** The second `.then()` method processes the parsed JSON data. Here, we can handle the data, such as logging it to the console.
5. `.catch(error => {...})`**:** The `.catch()` method handles any errors that occur during the fetch operation or while processing the response. This includes network errors and the errors thrown if the response is not ok.

## Read also,

[**Implementation of Data Structures in JavaScript**](https://www.mindstick.com/blog/304386/implementation-of-data-structures-in-javascript)

[**Explain the concept and use DOM Manipulation**](https://www.mindstick.com/blog/304387/explain-the-concept-and-use-dom-manipulation)


---

Original Source: https://www.mindstick.com/forum/160757/what-are-promises-in-javascript-and-how-do-they-work

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
