# Understanding Promise.all (with Custom Implementation)

### What is `Promise.all()`?

`Promise.all()` is used to run multiple promises in parallel and wait until all of them complete.

**Behavior:**

*   If **all promises resolve**, it returns a resolved promise with an array of results.
    
*   If **any one promise rejects**, it immediately returns a rejected promise with that error.
    
*   It **fails fast** — meaning it doesn’t wait for other promises once one fails.
    

**Example**

```javascript
const p1 = Promise.resolve(10);
const p2 = Promise.resolve(20);
const p3 = Promise.resolve(30);

Promise.all([p1, p2, p3])
  .then(result => {
    console.log(result); // [10, 20, 30]
  })
  .catch(err => {
    console.error(err);
  });
```

* * *

**Rejection Case**

```javascript
const p1 = Promise.resolve(10);
const p2 = Promise.reject("Error in p2");
const p3 = Promise.resolve(30);

Promise.all([p1, p2, p3])
  .then(result => {
    console.log(result);
  })
  .catch(err => {
    console.error(err); // "Error in p2"
  });
```

* * *

**Key Concept**

> `Promise.all()` follows **fail-fast behavior** — one failure stops everything.

* * *

### Custom Implementation of `Promise.all()`

Let’s now understand how `Promise.all()` works internally by implementing it ourselves.

* * *

### **Code**

```javascript
function promiseAll(promises) {
    return new Promise((resolve, reject) => {
        let arr = [];
        let completed = 0;

        if (promises.length === 0) {
            resolve([]);
        }

        promises.forEach((element, index) => {
            Promise.resolve(element)
                .then((data) => {
                    arr[index] = data;
                    completed++;

                    if (completed === promises.length) {
                        resolve(arr);
                    }
                })
                .catch(reject);
        });
    });
}
```
