What are promises in JavaScript? Explain with example.

What is a promise?

A Promise is an object that represents the fulfillment or failure of an asynchronous operation.

Why do we need Promise?

  • Promise objects handle asynchronous operations
  • It provides the ability to write cleaner code by reducing the call-back hell
  • It allows errors to be passed down the chain and handled in one common place so that the layers of error handling can be easily avoided

What are the states of promise?

A Promise is in one of these states:

pending: initial state, neither fulfilled nor rejected
fulfilled: meaning that the operation completed successfully
rejected: meaning that the operation failed

Example of promise:

const promiseToWriteReactApp = new Promise(function(resolve, reject){
    isWritten = (Math.random() < 0.5);
    (isWritten) ? resolve('resolved') : reject('rejected');
});

promiseToWriteReactApp.then(function(fromResolve){
    console.log(fromResolve);
}).catch(function(fromReject){
    console.log(fromReject);
});

Promise inside React component

Following is the code of a promise inside React component:


import React, {useEffect, useState} from 'react';
/*
 * Purpose: The purpose of this component is to understand JavaScript promise.
 *
 * Version: 1.0
 */

const PromiseEntity = () => {
    const [data, setData] = useState('');

    useEffect(() => {
        const promiseObj = new Promise((resolve, reject) => {
            if(Math.random() < 0.5) {
                resolve('success');
            } else {
                reject('Error');
            }
        });

        promiseObj.then((status) =>{
            console.log(status);
            setData(status);
        }).catch((error) => {
            console.log(error);
            setData(error);
        }).finally(() => {
            console.log('Promise completed');
        });
    }, []);

    return (
        <>
            <h1>Promise example: {data}</h1>
        </>
    );
};
export default PromiseEntity;

Important notes about promise

  • The code inside the promise constructor is synchronously executed.
  • then method takes as a first argument a callback which is asynchronously executed on promise fulfillment.
  • then method takes as a second argument a callback which is asynchronously executed on promise rejection. However we are usually using the catch method for this which also takes a callback which is asynchronously executed on promise rejection.
  • The then callback receives as a first argument the resolved value (the string 'success' in this case).
  • The catch callback receives as a first argument the rejected value (the string 'Error' in this case).
  • The finally method receives a callback which is executed on both promise fulfillment and rejection.

Multiple resolve/reject will have effect?

When a promise is resolved (or rejected), it is done. If we call then method on its promise again, we immediately get the (first) resolved/rejected result.

Additional calls to resolve() will not have any effect.
const promiseMultipleAction = new Promise((resolve, reject) => {
    resolve(1);
    reject(2);
    resolve(3);
});

promiseMultipleAction.then(status => console.log('It resolves to: ' + status))
    .catch(error => console.log('It never calls: ' + error));

promiseMultipleAction.then(status => console.log('one more call: ' + status));
promiseMultipleAction.then(status => console.log('two more calls: ' + status));
promiseMultipleAction.then(status => console.log('three more calls: ' + status));

// Output: 
It resolves to: 1
one more call: 1
two more calls: 1
three more calls: 1

Promise methods:

There are 6 methods of JavaScript Promise class as of April 2021. Those methods are:

  • Promise.all
  • Promise.allSettled
  • Promise.race
  • Promise.any
  • Promise.reject
  • Promise.resolve

Among all the promise methods Promise.all method is the most used.

Source: