0
\$\begingroup\$

I am currently migrating some code from class-based components to function components using hooks in React. Where I have come across a piece of code that works as expected but there are 3 Axios calls that are dependent on input from the first Axios call.

First Axios call returns order amount and merchant ID that are required for the second API to execute and the third API requires order ID and customer ID.

How can I deal with nested callbacks and write some clean, clear and readable code?

function getOrderDetails(customerId, token) {
  const orderDetailsPayload = {
    customerId,
    source: 'source'
  };
  setLoader(true);
  firstApi(orderDetailsPayload, token)
    .then(res => {
      setMerchantName(res.merchantName);
      setMerchantRedirectLink(res.merchantPlatformLink);
      if (res.orderAmount) {
        orderDetails(res);
        const emiPayload = {
          orderAmount: res.orderAmount,
          merchantId: res.merchantId
        };
        secondApi(emiPayload)
          .then(res => {
            console.log('EMI Response : ', res);
            if (res.data.status_code === 200) {
              setLoader(false);
              emiDetails(res.data);
            } else {
              setLoader(false);
              setAlert(true);
              console.log('EMI Details not present');
              setErrorMsg(res.data.message);
              setRoute('SignUp');
            }
          })
          .finally(() => {
            setLOADERemiCalculator(false);
          });
        const redirectionPayload = {
          customerId,
          orderId: res.orderId
        };
        thirdApi(redirectionPayload).then(res => {
          console.log('Redirection Response : ', res);
          if (res.data.status_code === 200) {
            setLoader(false);
            redirectionDetails(res.data);
            setRedirection(true);
            setMerchantRedirectLink(res.data.redirectionInfo.redirectionUrl);
          } else {
            setLoader(false);
            setRedirection(false);
            console.log('Redirection URL not present');
          }
        });
      } else {
        setLoader(false);
        setAlert(true);
        console.log('Order Amount missing');
        setErrorMsg(
          'Oops something went wrong please contact customer care'
        );
        setLOADERemiCalculator(false);
        setRoute('SignUp');
      }
    })
    .catch(exception => {
      setLoader(false);
      console.log('getCheckoutApprovedProduct exception : ', exception);
      setAlert(true);
      setErrorMsg(
        'Oops something went wrong please contact customer care'
      );
      setRoute('SignUp');
    })
    .finally(() => {
      setLOADERgetOrderDetails(false);
      console.log('Finally block:getOrderDetails');
    });
}
\$\endgroup\$
4
  • 2
    \$\begingroup\$ The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How do I ask a good question?. \$\endgroup\$
    – BCdotWEB
    Sep 29, 2021 at 6:38
  • \$\begingroup\$ I have rolled back Rev 2 → 1. Please see What to do when someone answers. \$\endgroup\$ Sep 29, 2021 at 15:10
  • 3
    \$\begingroup\$ Please edit your question so that the title describes the purpose of the code, rather than its mechanism. We really need to understand the motivational context to give good reviews. Thanks! \$\endgroup\$ Sep 29, 2021 at 15:47
  • \$\begingroup\$ The best thing I can think of is to break this up into many smaller functions. This thing is pretty large and nested. \$\endgroup\$ Sep 29, 2021 at 21:05

1 Answer 1

1
\$\begingroup\$

You can use the async/await syntax, its purpose is exactly cleaning up nested callbacks like this.

\$\endgroup\$
2
  • \$\begingroup\$ I have added async and await to my code and updated my question. Please check. \$\endgroup\$
    – anup
    Sep 29, 2021 at 7:55
  • \$\begingroup\$ You need to put an await for each promise. You can check this guide from MDN for a starter on this. \$\endgroup\$ Sep 30, 2021 at 10:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.