Creating a Promise, Chaining & Error Handling

Creating a Promise, Chaining & Error Handling

In the last post, we learned how to consume a promise. In this article, we will learn how to create our own promise, error handling, and promise chaining.

CASE 1 - if your validateCart is returning true, the promise will be resolved (success)

const cart = ["shoes", "pants", "kurta"];

const promise = CreateOrder(cart);

promise
  .then(function (orderId) {
    console.log(`order id ${orderId}`);
    return orderId;
  })

function CreateOrder(cart) {
  let pr = new Promise(function (resolve, reject) {

    if (!validateCard(cart)) {
      const err = new Error("cart validation failed");
      reject(err);
    }

    const orderId = "12345";
    if (orderId) {
      setTimeout(() => {
        resolve(orderId);
      }, 3000);
    }
  });
  return pr;
}

function validateCard() {
  return true;
}        

  • JS provides a Promise constructor through which we can create a promise.
  • It accepts a callback function with two parameters to resolve & reject


What is this resolve and reject?

These functions are passed by javascript to us to handle the success and failure of function calls.

  • In the Above Example, we assume that in a real-world scenario, validateCart would be defined.
  • In Case - 1 we created a validateCard function and set it to true it means our cart is validated right now so the above promise will be resolved (success)


What will be printed in the console?

It prints Promise {<pending>}, but why?

Because the above createOrder function will take some time to get resolved, so initially it is pending But once the promise is resolved, .then will be executed for the callback and we will get orderId in the console.


CASE 2 - Now let's see if there was some error and we are rejecting the promise, how can we catch that?

-> Using .catch

Now our validateCard function will return false, meaning the promise will be rejected and our browser will throw an error.

const cart = ["shoes", "pants", "kurta"];

promise
promise
  .then(function (orderId) {
    console.log(`order id ${orderId}`);
    return orderId;
  })
  .catch(function (err) {
    console.log(err);
  });

function CreateOrder(cart) {
  let pr = new Promise(function (resolve, reject) {

    if (!validateCard(cart)) {
      const err = new Error("cart validation failed");
      reject(err);
    }

    const orderId = "12345";
    if (orderId) {
      setTimeout(() => {
        resolve(orderId);
      }, 3000);
    }
  });
  return pr;
}

function validateCard() {
  return false;
}        

Output - Error: cart validation failed.


Now, Let's understand the concept of Promise Chaining

-> For this we will assume after createOrder we have to invoke proceedToPayment

-> In promise chaining, whatever is returned from the first .then become data for the next .then and so on...

-> At any point of promise chaining, if the promise is rejected, the execution will fallback to .catch and others promise won't run.

const cart = ["shoes", "pants", "kurta"];

promise
  .then(function (orderId) {
    console.log(`order id ${orderId}`);
    return orderId;
  })

  .then(function (orderId) {
    return proceedToPayment(orderId);
  })

  .then(function (paymentInfo) {
    console.log(paymentInfo);
  })

  .catch(function (err) {
    console.log(err);
  });

function proceedToPayment(orderId) {
  return new Promise(function (res, rej) {
    if (orderId) {
      res("Payement Successfully Done");
    }
  });
}

function CreateOrder(cart) {
  let pr = new Promise(function (resolve, reject) {
    if (!validateCard(cart)) {
      const err = new Error("cart validation failed");
      reject(err);
    }
    const orderId = "12345";
    if (orderId) {
      setTimeout(() => {
        resolve(orderId);
      }, 3000);
    }
  });
  return pr;
}

function validateCard() {
  return true;
}
        

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics