javascript

Promise in JavaScript

Promise in JavaScript

In this tutorial, we are going to learn about how to use promises in javascript.

What is a Promise?

Promises are an ES6 feature and they became available in JavaScript in 2015.

Basically, Promise is an object that is used basically as a placeholder for the future result of

an asynchronous operation.

we can also say that a promise is like a container for a future value.

Using promises we can escape callback hell

Promises in JavaScript

Promises are essentially just a special kind of object in JavaScript.

we usually only built promises to basically wrap old callback-based functions into promises.

And this is a process that we call promisifying.

So basically promisifying means to convert callback-based asynchronous behavior

to promise-based.

Now, since promises work with asynchronous operations,they are time sensitive.

So they change over time.

And so promises can be in different states and this is what they call the cycle of a promise.

So in the very beginning,

we say that a promise is pending.

And so this is before any value resulting from the asynchronous task is available.

Now, during this time, the asynchronous task is still doing its work in the background.

Then when the task finally finishes, we say that the promise is settled and there

are two different types of settled promises and that's fulfilled promises and rejected promises.

So a fulfilled promise is a promise that has

successfully resulted in a value just as we expect it.

For example, when we use the promise to fetch data from an API,

a fulfilled promise successfully gets that data, and it's now available to being used.

On the other hand,a rejected promise means that there has been an error during the asynchronous task.

And the example of fetching data from an API,an error would be for example,

when the user is offline and can't connect to the API server.

There are 3 states of the Promise object:

  • Pending: Initial State, before the Promise succeeds or fails
  • Resolved: Completed Promise
  • Rejected: Failed Promise

Building a Simple Promise

we can create a new promise using the promise constructor, as shown below.

const myPromise = new Promise();

It takes two parameters, one for success (resolve) and one for fail (reject):

const myPromise = new Promise((resolve, reject) => {  
    // condition
});

Finally, there will be a condition. If the condition is met, the Promise will be resolved, otherwise, it will be rejected:

const myPromise = new Promise((resolve, reject) => {  
    let condition;  
    
    if(condition is met) {    
        resolve('Promise is resolved successfully.');  
    } else {    
        reject('Promise is rejected');  
    }
});

So we have created our first Promise. Now let's use it.

then( ):

The then( ) method is called after the Promise is resolved.

For example, let’s log the message to the console that we got from the Promise:

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

catch( ):

We can use the catch() method to handle failed or rejected promises, see below example:

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

So if the promise gets rejected, it will jump to the catch( ) method

finally( ):

Now the finally method is not always useful, but sometimes it actually is.

So we use this method for something that always needs to happen

no matter the result of the promise, And one good example of that is to hide a loading spinner

myPromise.then((message) => { 
if (message!== ‘hello’){
     throw new Error(“Oops, you didn’t type hello”)
   }
}).catch((message) => { 
    console.log(message);
},finally {
   alert(‘thanks for visiting!’)
});

whenever we want to create some error that we want to handle down here,

in the catch handler, all we need to do is to throw, because throwing an error inside of this callback function of this then method will immediately reject this promise.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment