Promises

Open browser console to view the output

Promise is an object that represents eventual completion or rejection of asynchronous operations

Promises has 3 major states

  • Pending: The async operation is in the pending state
  • Resolved (Fullfilled): the promise has completed its's async operation & has returned some data
  • Rejected:the promise has rejected to perform async operation with an exception thrown

Finally method: One of the promise method which is not concerned if the promise is resolved or rejected. This is accessed as promise.finally(function(){}), just the same way as .then() & .catch() method

Promise returns 2 major data which can be viewed in the browser console

  • [PromiseResult] - the response
  • [PromiseState] - pending, fullfilled or rejected

2 very imporatnt things to remember

  • always return the promise which most of the developers forget this days
  • if .catch() is excecuted before .then() then all the errors of prev .then() functions will be handled & definetely the next then() function is executed

Promises were introduced to handle asynchronous operations mainly callback functions had 2 major problems

  • Inversion of control -> solution is to use promise
  • Callback hell -> use of .then() method in a systematic way

Below is the example of callback hell - it's a nested functions

        createOrder(cart, function (orderId) {
            proceedToPayment(orderId, function (paymentInfo) {
                ShowOrderSummary(paymentInfo, function () {
                    updateWallet(walletInfo);
                });
            });
         });
        

The same above code snippet can be achieved in a systematic way using promise

            var cart = ["Bhagvat Gita", "Sutras", "Asanas", "Pranayamas"];
            // return order ID
            function createOrder() {
                return new Promise(function (resolve, reject) {
                    if (!validateOrder()) {
                        var err = new Error("The cart has no items in it");
                        reject(err);
                    } else {
                    // Say suppose an API is returning order Id - 12345;
                       const orderId = "12345";
                       resolve(orderId);
                    }
                });
            }

            function validateOrder() {
                return true;
            }

            // return payment info i.e. success or failure
            function proceedToPayment(orderId) {
                return new Promise(function (resolve, reject) {
                    if (!orderId) {
                        reject("Order Id is not valid");
                    } else {
                        resolve("Payment is successful");
                    }
                });
            }

            // returns the number of items purchased
            function ShowOrderSummary(paymentInfo) {
                return new Promise(function (resolve, reject) {
                    if (!paymentInfo) {
                        reject("Payment has failed");
                    } else {
                    resolve("Payment is successful");
                    }
                });
            }

            // return wallet info
            function updateWallet(walletInfo) {
                return new Promise(function (resolve, reject) {
                    if (cart.length === 4) {
                        resolve(walletInfo + "Wallet is updated");
                    } else {
                        reject("Please make the neccessary payment");
                    }
                });
            }

            createOrder()
            .then(function (orderId) {
                return proceedToPayment(orderId);
            })
            .then(function (paymentInfo) {
                return ShowOrderSummary(paymentInfo);
            })
            .then(function (walletInfo) {
                console.log("walletInfo - " + walletInfo);
                return updateWallet(walletInfo);
            })
            .catch(function (err) {
                console.log("err : " + err);
            });