All (or just most) of what you need to know about handling Promises
Tags: promise, javascript, async, explainlikeimfive
Published: 2019-10-06 09:06:05

I Don't use Promises on a daily basis. But when I do, all I need is a simple usage example of how to handle them. What I find instead are over complex examples, many articles about _async programming_ and the _theory_ behind Promises in JavaScript.
I end up re-learning Promises for a few minutes to realize that in most cases there are only 2 - 3 main ways I actually handle the Promises.

So, I made a [Github repository called "Promise Sandbox"](https://github.com/ori-volfo/promise-sandbox) with the 3 main usages that I need, and made sure that the code will be as short and as simple as possible.
In this example, I only execute 2 Promises. A long one and a short one.
You can add more but it will only make the code longer and more complex, and it will not get you any more insights.

Let's dive straight into code!
## Promise execution
So, I am executing 2 simple Promises here. currently set to resolve (you can flip the annotations if you would like them to be rejected).
longPromise - set to be resolved after 10 seconds.
shortPromise - set to be resolved after 2 seconds.
```javascript
var longPromise = ()=>{
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve('longPromise resolved');
            // reject('longPromise rejected');
        }, 10000);
    })
};

var shortPromise = ()=> {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve('shortPromise resolved');
            // reject('shortPromise rejected');
        }, 2000);
    })
};
```
## Handling Options
### Classic chaining
The good old way to handle Promises.
This is a shortcut to find yourself in _callback hell_.
```javascript
longPromise()
    .then((data)=>{
        console.log(data); // logs: longPromise resolved
        shortPromise()
            .then((data)=>{
                console.log(data) // logs: shortPromise resolved
            })
            .catch((data)=>{
                console.log(data) // logs: shortPromise rejected
            })
    .catch((data)=>{
        console.log(data) // logs: longPromise rejected

        // shortPromise is unhandled in case longPromise was rejected
    });
});
```

#### Edited:
As bloggers [Eugene Karataev](https://dev.to/karataev) and [Joel Ruiz](https://dev.to/joetex) suggested, we can dodge callback hell simply by **returning** the following Promise, instead of just calling it.
This will flatten our nesting and make the code much more readable:
```javascript
longPromise()
    .then((data)=> {
        console.log(data); // logs: longPromise resolved
        return shortPromise();
    })
    .then((data)=>{
        console.log(data) // logs: shortPromise resolved
    })
    .catch((error)=> {
        console.log(error); // One catch to reject them all!
    });
```

### Promise all
Batching all promises into an array. Handling **all at once**. 
If you are using _Node_, i suggest you `JSON.stringify` the logged data.
```javascript
Promise.all([longPromise(), shortPromise()]).then(function(data) {
    console.log(data);
});
```

### Async await (Thank you ES6!)
Or actually ES8, to be more accurate.
If you don't want to deal with the async quirks of JS, let the new _async-await_ functionality to take care of it. make sure you wrap your **await**s in an **async** function.
In this example, i made the async function to be an [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) to make sure that it invokes Immediately.
```javascript
(async ()=>{
    let long = await longPromise();
    let short = await shortPromise();
    console.log(long);   // logs: longPromise resolved
    console.log(short);  // logs: shortPromise resolved
})();
```
This should work fine on any browser (Except IE. IE is not a browser!).


## All the rest that was not mentioned
* If you don't care whether the promise is resolved or reject, when handling a single promise use `.finally()` instead of `.then()` and/or `.catch()`.
*  In addition to `Promise.all()` you also have `Promise.race()` which is like `Promise.all()`, but will be invoked once the first promise is fulfilled.
* There is also the `Promise.allSettled()` which is still new, and not yet supported by most browsers and Node below version 12.9.