Promises

  • As the term suggests , Promise is a promise that tells us that something (either the value or the reason it doesn't have value )will be available in the future.
  • It's an object that keeps track about whether a certain event has happened or not.
  • It also Determines what happens to result.

#  These Promises come with States

promises

  1. Pending: before the event happens;
  2. Settled/Resolved: after the event happens;
  3. Fulfilled: when the promise returns the correct result;
  4. Rejected: when the promise does not return the correct result.

states of promises

Simple Right ? Now Let's see how do we make a Promise .

Take this below code and paste it on your console or code editor

const API_URL = 'https://randomuser.me/api/';
const responsePromise = fetch(API_URL);
console.log(responsePromise); //promise pending

responsePromise.then((response) => {
console.log(response);
})

responsePromise.catch((error) => {
console.log(error);
})

Here, We use  fetch API which returns HTTP response as a promise.

Image for post

# pending

On line 3 we see that the promise is pending because promises are asynchronous and therefore take time to settle.

# then()

Promises have a then method that is executed when the promise has been fulfilled. It receives a callback.

You can see the output of this as an object. Since the response has a status code of 200 that means our request is successful.

Image for post

#catch()

Let’s say we have an error (invalid url, non-existent end point, server connection timeout, etc.) while making a request, then we can catch those errors using catch(). Like then(), it also receives a callback.


# Creating a Promise !

var promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve();
    }, 1000);
});

//Now lets also add then and catch methods to handle the promise

promise
    .then(() => {
    console.log('Fulfilled');
})
    .catch((err) => {
    console.log('Rejected');
});

In the example above, we are producing a promise using new keyword . You may notice that the promise object receives a callback function that accepts two arguments: resolve and reject. This callback is called an executor function, and it is called immediately when the promise is created.

The executor function informs the promise of whether or not the event was successful. If it was successful, the function "resolve" is called. If it was unsuccessful, the "reject" function is called.

Image for post

We can also handle both resolve and reject something like the following.

function makePromise(bool) {
    return new Promise((resolve, reject) => {
        if (bool) resolve();
        reject();
    });
}

makePromise(true)
    .then(() => console.log('I am fullfilled :)'))
    .catch(() => console.log('I am rejected  :( '));

Remember: Whenever resolve is true, the promise executes then() and catch() otherwise


#Async/Await

Async /await is another alternative for consuming promises, and it was implemented in ES8, or ES2017.

async function fetchResult (){

    var result = await  fetch('https://randomuser.me/api/')
    .then(response => response.json())
    
    console.log(result,"Prints result");
}

fetchResult()

So here's what happened in the code above: We created an async function using the async keyword before the function. This means that this function is asynchronous, which means it basically runs in the background.The keyword await makes JavaScript wait until that promise settles and returns its result. With async and await we can write cleaner asynchronous code.

Yay !! You are all set now . You can try implementing and experimenting with what you have learned !