Promises in JavaScript

What are promises?

A promise is an object whose value will be determined in the future.

Lets look at an example:

Say you want to get some data from a remote resource like an API or a database, After you make the request, the remote resource will take a small amount of time to fetch and return the data to you. A promise is simply an object which will have a value when the data is returned.


Browser support

Promises are enabled by default in Chrome 32+, Opera 19+, Firefox 29+, Safari 8+ and Microsoft Edge. If your browser does not support promises, you can simply add the polyfill using one of the available CDNs

Promise states

A promise can be in one of three states

fulfilled  – a promise is said to be fulfilled if the event that we have waited for has completed successfully and the result is available to be used

rejected  –  a promise is said to be rejected if the event that we are waiting for has completed erroneously. 

pending – a promise is pending if it has neither fulfilled nor rejected.

Creating a Promise

Creating promises in javascript is simple, you use the new keyword since Promises are objects and you are creating an object, followed by the keyword Promise

new Promise();

The promise takes in a function as callback with two parameters, resolve and reject. You can pass in the value to be returned to the resolve parameter, you can pass the error to be returned to the reject parameter.

Example:

//create a new promise

var promise = new Promise((resolve, reject)=>{
     //promise resolves after 3 seconds
     setTimeout(()=>{
         resolve(true);     
     }, 3000)
});


//handle the promise
promise.then(success=>{
     //the promise resolved successfully
     console.log('promise completed')
}, error=>{
     //the promise failed with an error
     console.error(error);
});

As shown in the above example, the promise object has a then method which is used to access the value returned by the promise after the promise has resolved.

Promise Chaining

The promise then()  can also be chained together to transform values or run additional async actions one after another.

Example:

checkIfUserLoggedIn().then(user=>{
     //user logged in
     console.log('promise completed')
     return user
}, error=>{
     //user not logged in
     console.warn(error);
}).then((user)=>{
     getProfile(user);
})

Multiple Promises

Suppose you have multiple promises and you want to run a function once all the promises have resolved, you can do this using the Promise.all() method by passing in an array of promises

var promiseArray = [promise1, promise2, promise3];
Promise.all(promiseArray).then((resolvedArray)=>{
     resolvedArray.forEach(p=>{
          console.log(p);
     }
)}

In the above section of code, promiseArray is an array of promises, we then pass the array to the Promise.all method, next in the then callback, we receive an array which contains the resolved values of all the promises.

Share this!

One thought on “Promises in JavaScript”

Leave a Reply

Your email address will not be published. Required fields are marked *