JavaScript Promise methods Explained!
Tags: javascript, webdev
Published: 2021-07-15 10:00:17

### What is Promise?
The Promise is a simply improved version of callbacks, and JavaScript's Promise is effectively the same as Promise in real life. You make a promise to do something, and either does it and succeed or do not do it and fail. That is how JavaScript's Promise works.
A Promise is essentially saying, "Hey, I'm going to execute some code, and if I'm successful, I'll let you know and give you the result," and "If I'm unsuccessful, I'll let you know and just tell you the error that goes with that code."

```javascript
const promise = new Promise((resolve, reject) => { 
// resolve- happens when you successfully complete the promise
// reject - happens when you failed to complete the promise
const sum = 10 + 10
if (sum === 20) {
		resolve("Success");
	} else {
		reject("Error");
	}
});

promise
	.then(message => {
	console.log(message);
}) 
	.catch(message => {
	console.log(message);
})

// Output -> Success
```
----

_Let's look at Promise methods_

### Promise.all()

→ **Promise.all()** is used to run multiple promises, we need to pass an array of different promises, and then we can do things based on whether they all fail or some of them fail or they all succeed or some of them succeed. 

**`resolve()`** → returns a successful promise.

**`reject()`** → returns a failed promise.

```javascript
Promise.all([
    Promise.resolve("1"),
    Promise.resolve("2"),
    Promise.resolve("3"),
]).then(messages => {
	console.log(messages)
})

// Output -> ["1", "2", "3"]
```

In the above code snippet, all three `Promise` have been successfully resolved and they have the message "1", "2", "3" inside of them. The messages array is the return value of all our promises in order from top to bottom.

```javascript
Promise.all([
    Promise.resolve("1"),
    Promise.resolve("2"),
    Promise.reject("Error on 3"),
    Promise.reject("Error on 4"),
]).then(messages => {
	console.log(messages)
}).catch(error => {
	console.error(error)
})

// Output -> Error on 3
```

In the above code snippet only the rejected value is printed from the `.catch()` block and nothing gets printed from the `.then()` block.

This happens because the `Promise.all()` only calls `.then()` when every single `Promise` inside it succeeds or is resolved. If one of them fails it will call `.catch` and print the result of the first failed or rejected `Promise`.

----- 

### Promise.any()

 → It takes the array of multiple promises and It returns any of the first `Promise` that gets succeeds or resolved, you can imagine a bunch of different `Promise` taking various amount of time to execute, the first one to get executed will return the value in `.then()`

```javascript
Promise.any([
    Promise.resolve("1"),
    Promise.reject("Error on 2"),
    Promise.reject("Error on 3"),
    Promise.resolve("4"),
]).then(message => {
	console.log(message)
}).catch(error => {
	console.error(error)
})

// Output -> 1

Promise.any([
    Promise.reject("Error on 1"),
    Promise.reject("Error on 2"),
    Promise.resolve("3"),
    Promise.resolve("4"),
]).then(message => {
	console.log(message)
}).catch(error => {
	console.error(error)
})

// Output - 3
```

----- 

### Promise.race()

→ It takes an array of multiple promises, It is like `Promise.any()` but instead of getting the first promise that succeeds, `Promise.race()` returns the first `Promise` that finishes whether or not it succeeds or fails.

```javascript
Promise.race([
    Promise.reject("Error on 1"),
    Promise.reject("Error on 2"),
    Promise.resolve("3"),
    Promise.resolve("4"),
]).then(message => {
	console.log(message)
}).catch(error => {
	console.error(error)
})

// Output -> Error on 1

Promise.race([
    Promise.resolve("1"),
    Promise.resolve("2"),
    Promise.reject("Error on 3"),
    Promise.reject("Error on 4")
]).then(message => {
	console.log(message)
}).catch(error => {
	console.error(error)
})

// Output -> 1
```

The code above is not `asynchronous` it is getting executed from top to bottom but if were to imagine it has the timeout and it took a given of time to succeed or fail. The example is given below.

```javascript
Promise.race([
     Promise.resolve("1"), // 100 ms
     Promise.resolve("2"), // 400 ms
     Promise.reject("Error on 3"), // 200 ms
     Promise.reject("Error on 4") // 20 ms
]).then(message => {
	console.log(message)
}).catch(error => {
	console.error(error)
})

// Output -> Error on 4
```

The above code snippet will print `Error on 4` because it will be the first one to finish its execution.

----- 

### Promise.allSettled()

→ It takes an array of multiple promises, `Promise.allSettled()` waits for all the Promises to finish whether they get rejected or they get fulfilled it doesn't matter it waits for every single `Promise` to finish.

```javascript
Promise.allSettled([
    Promise.resolve("1"),
    Promise.resolve("2"),
    Promise.reject("Error on 3"),
    Promise.reject("Error on 4")
]).then(messages => {
	console.log(messages )
}).catch(error => {
	console.error(error)
})

/* Output -> (4) [{…}, {…}, {…}, {…}]
0: {status: "fulfilled", value: "1"}
1: {status: "fulfilled", value: "2"}
2: {status: "rejected", reason: "Error on 3"}
3: {status: "rejected", reason: "Error on 4"}
length: 4
*/
```

As you can see `Promise.allSettled()` prints the 4 objects and 
the object contains the **`status`** which is *`rejected`* or *`fullfilled.`*
**`reason`** if the **`status`** is *`rejected`* 
**`value`** if the **`status`** is *`fulfilled`*.

```javascript
Promise.allSettled([
    Promise.reject("Error on 1"),
    Promise.reject("Error on 2"),
    Promise.reject("Error on 3"),
    Promise.reject("Error on 4")
]).then(messages => {
	console.log(messages )
}).catch(error => {
	console.error(error)
})

/* Output -> (4) [{…}, {…}, {…}, {…}]
0: {status: "rejected", reason: "Error on 1"}
1: {status: "rejected", reason: "Error on 2"}
2: {status: "rejected", reason: "Error on 3"}
3: {status: "rejected", reason: "Error on 4"}
length: 4
*/
```

In the above code snippet as you can see it still calls the `.then()` even after all the `Promise` got rejected, because `Promise.allSettled()` will always call `.then` even if the `Promise` gets fulfilled or rejected.

*Thank you for making it till the end!*