Javascript Promise Methods with polyfill example: A Cheat Sheet for Developer
Tags: javascript, promise, beginners, interview
Published: 2022-11-14 06:50:00

Promise helps to do something asynchronously, It is a way to handle asynchronous operations in JavaScript.

[![All You Need to Know About JavaScript Promises methods and Polyfill](https://img.youtube.com/vi/-PksSsfYVw4/0.jpg)](https://youtu.be/-PksSsfYVw4?autoplay=1)

## Promise consists of three states:

1. Pending: Initial State, neither fulfilled nor rejected.
2. Fulfilled: Completed Promise (success)
3. Rejected: Failed Promise (failure)

Without wasting time, Let's learn about the Promise functions.

##### Note: I've also added a Polyfill example, Which will help you to understand easily and also help you if you are preparing for the interview.

---

### 1. Promise.all

Promise.all takes an array of promises as input and returns a promise object. The returned promise will be resolved when all the promises in the input array are resolved. If any of the promises in the input array is rejected, the returned promise will be rejected with the reason for the first rejected promise.

###### Example:

```js
const promises = [1, 2, 3].map((item) => Promise.resolve(item));
Promise.all(promises).then(console.log); // [1, 2, 3]
```

###### Polyfill Example:

```js
const all = (promises) => {
  return new Promise((resolve, reject) => {
    const result = [];
    let count = 0;
    for (let i = 0; i < promises.length; i++) {
      Promise.resolve(promises[i]).then((res) => {
        result[i] = res;
        count++;
        if (count === promises.length) {
          resolve(result);
        }
      }, reject);
    }
  });
};
```

---

### 2. Promise.race

It takes an array of promises as input and returns a promise object. The returned promise will be resolved/rejected as soon as one of the promises in the input array is resolved/rejected.

###### Example:

```js
const promises = [Promise.resolve(1), Promise.reject(2), Promise.resolve(3)];
Promise.race(promises).then(console.log); // 1
```

###### Polyfill Example:

```js
const race = (promises) => {
  return new Promise((resolve, reject) => {
    promises.forEach((promise) =>
      Promise.resolve(promise).then(resolve, reject)
    );
  });
};

const promises = [Promise.resolve(1), Promise.reject(2), Promise.resolve(3)];
race(promises).then(console.log); // 1
```

---

### 3. Promise.allSettled

It takes an array of promises as input and returns a promise object. The returned promise will be resolved when all the promises in the input array are settled. The returned promise will be resolved with an array of objects that each describes the outcome of each promise in the input array.

###### Example:

```js
const promises = [Promise.resolve(1), Promise.reject(2), Promise.resolve(3)];
Promise.allSettled(promises).then(console.log); // [{status: "fulfilled", value: 1}, {status: "rejected", reason: 2}, {status: "fulfilled", value: 3}]
```

###### Polyfill Example:

```js
const allSettled = (promises) => {
  return new Promise((resolve) => {
    const result = [];
    let count = 0;

    const handleResult = (value, index, status) => {
      result[index] = { status, value };
      count++;
      if (count === promises.length) {
        resolve(result);
      }
    };

    for (let i = 0; i < promises.length; i++) {
      Promise.resolve(promises[i]).then(
        (res) => handleResult(res, i, "fulfilled"),
        (err) => handleResult(err, i, "rejected")
      );
    }
  });
};

const promises = [Promise.resolve(1), Promise.reject(2), Promise.resolve(3)];
allSettled(promises).then(console.log); // [{status: "fulfilled", value: 1}, {status: "rejected", reason: 2}, {status: "fulfilled", value: 3}]
```

---

### 4. Promise.any

It takes an array of promises as input and returns a promise object. The returned promise will be resolved when any of the promises in the input array is resolved. If all of the promises in the input array are rejected, the returned promise will be rejected with an error array.

###### Example:

```js
const promises = [Promise.reject(1), Promise.reject(2), Promise.resolve(3)];
Promise.any(promises).then(console.log); // 3
```

###### Polyfill Example:

```js
const any = (promises) => {
  return new Promise((resolve, reject) => {
    const result = [];
    let count = 0;

    const handleResult = (value, index, status) => {
      result[index] = { status, value };
      count++;
      if (count === promises.length) reject(result);
    };

    for (let i = 0; i < promises.length; i++) {
      promises[i].then(resolve, (err) => handleResult(err, i, "rejected"));
    }
  });
};

const promises = [Promise.reject(1), Promise.reject(2), Promise.resolve(3)];
any(promises).then(console.log); // 3
```

---

### 5. Promise.resolve

It returns a resolved promise.

###### Example:

```js
Promise.resolve(1).then(console.log); // 1
```

###### Polyfill Example:

```js
const resolve = (value) => {
  return new Promise((resolve) => resolve(value));
};

resolve(1).then(console.log); // 1
```

---

### 6. Promise.reject

It returns a rejected promise.

###### Example:

```js
Promise.reject(1).catch((err) => console.log(err)); // 1
```

###### Polyfill Example:

```js
const reject = (value) => new Promise((resolve, reject) => reject(value));

reject(1).catch((err) => console.log(err)); // 1
```

---

Thank you for reading 😊

Got any questions or additional? please leave a comment.

---

##### Must Read If you haven't

###### [3 steps to create custom state management library with React and Context API](https://dev.to/devsmitra/3-steps-to-create-custom-state-management-library-with-react-hooks-and-context-api-1bfh)

###### [How to cancel Javascript API request with AbortController](https://dev.to/devsmitra/how-to-cancel-javascript-api-request-with-abortcontroller-36cm)

###### [Getting started with SolidJs – A Beginner's Guide](https://dev.to/devsmitra/getting-started-with-solidjs-a-beginners-guide-5af4)

---

###### More content at [Dev.to](https://dev.to/devsmitra "Rahul Sharma(DevsMitra)").

###### Catch me on [Youtube](https://www.youtube.com/channel/UCQkvNcHN5vg3jEoeOb9Tdrw?sub_confirmation=1 "Rahul Sharma(DevsMitra)"), [Github](https://github.com/devsmitra "Rahul Sharma(DevsMitra)"), [Twitter](https://twitter.com/devsmitraa "Rahul Sharma(DevsMitra)"), [LinkedIn](https://www.linkedin.com/in/rahul-sharma-18b8b374 "Rahul Sharma(DevsMitra)"), [Medium](https://devsmitra.medium.com "Rahul Sharma(DevsMitra)"), [Stackblitz](https://stackblitz.com/@devsmitra "Rahul Sharma(DevsMitra)"), [Hashnode](https://devsmitra.hashnode.dev "Rahul Sharma(DevsMitra)"), [HackerNoon] (https://hackernoon.com/u/devsmitra "Rahul Sharma(DevsMitra)"), and [Blogspot](https://devsmitra.blogspot.com "Rahul Sharma(DevsMitra)").