JS Promise
Tags: javasciprt, promise
Published: 2019-05-11 21:53:50

---
title: JS Promise
published: true
description: Small guide to give basic understanding of JS Promise
tags: Javasciprt, promise
cover_image: https://thepracticaldev.s3.amazonaws.com/i/u4c0xg9fy0jnq5d5rsai.jpg
---

A Promise is an object representing the eventual completion or failure of an async operation. Essentially, a promise is returned object to which you attach callback, instead of passing callback into a function.

A Promise is one of these states:
<ul>
<li><b><i>Pending:</i></b> Initial(default) state, neither fulfilled nor rejected.</li>
<li><b><i>Fullfilled:</i></b> Operation completed successfully</li>
<li><b><i>Rejected:</i></b> Operation Failed</li>
</ul>

Pending promise can either be full-filled with a value, or rejected with a reason (error). when either of these options happens, the associated handlers queued up by a promise's <i>then</i> method are called.

### Three main questions about the promises
<ul>
<ol>1.How to create a Promise</ol>
<ol>2.How to change the status of a promise</ol>
<ol>How to listen for when status of a promise changes</ol>
</ul>

### How to create a Promise
A Promise object is created using the new keyword and its constructor.
<code>const promise = new Promise()</code>


### How to change the status of a promise
The Promise constructor a single callback function which takes two args. <i>resolve</i> callback function called when the result of the promise is resolve and <i>reject</i> callback function is called when the result of the promise is to rejected.

```javascript
const promise = new Promise((resolve, reject)=>{
    resolve(); // When the promise is fulfilled it change the status of the promise to resolve
    reject(); // When the promise is rejected it change the status of the promise to rejected.
})
```

### How to listen for when status of a promise changes
We can listen to the changes to the two method available with promises. 

<i>.then</i>If promise is fulfilled(resolve) the function attached to .then method is invoke
<i>.catch</i>If promise is rejected(rejected) the function attached to .catch method invoke

If you log the empty promise you can see the method attached to it's prototype.

![Promise console](https://thepracticaldev.s3.amazonaws.com/i/ypt70mb3tgsxkcbmrzzu.png)

Simple Example

{% gist https://gist.github.com/vish448/13d091b8d894dcbf46a485325fdc6b3a.js %}




### Methods

<i>Promise.all(iterable)</i>
<p>Returns a promise that either fulfills when all of the promises in the iterable args have fulfilled or rejects as soon as one of the promises in the iterable args rejects.</p>

if  the returned promise fulfills, it is fulfilled with an array of the values from the fulfilled promises in the same order as defined in the iterable.

If the returned promise rejects, it is rejected with reason from the first promise in the iterable that rejected.

<i>Promise.race(iterable)</i>
Returns a promise that fulfills or rejects as soon as one of the promises in the iterable fulfills or rejects, with the value or reason from that promise.

<i>Promise.reject(reason)</i>
Returns a Promise object that is rejected with the given reason.

<i>Promise.resolve(value)</i>
Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.


### How promises make confusing callback code lil easier



Old ways of doing several async operation in a row will create classic callback pyramid of doom

```javascript
doSomthing(function(result)){
    doSomethingElse(result, function(newResult){
        doThirdThing(newResult, function(finalResult){
            console.log(finalResult)
        }, failureCallback);
    }, failureCallback);
},failureCallback);
```
With modern functions, we attach our callbacks to the returned promises instead, forming a promise chain:

```javascript
doSomething()
.then(result=> doSomethingElse(result));
.then(newResult => doThirdThing(newResult));
.then(finalResult => console.log(finalResult));
.catch(failureCallback)
```
Now you can compare which is easy to read and follow.

###Codesandbox

Adding the codesandbox.

1. OnClick it will call a function which is returning a promise !
[axios.get](https://alligator.io/react/axios-react/)

2. Once the promise gets resolved it will call another function ".then" which is generating an actual UI for our component.

{% codesandbox jl4pojjoq3 %}