-1

I have a requirement where i need to invoke an api from within a client side Javascript function and once i get the response from the api i should use the response to construct a variable value. My function looks like below. The problem i am facing is that before the function could return the complete api response the next line to calculate totalAmt gets executed and as chkresponse1 is empty then the variable totalAmt is not being calculated correctly. And FYI getCheckFinalAmount() internally invokes the api using XMLHTTPRequest.

How do i ensure that totAmt gets calculated only after the api response is obtained? Any code snippets will be very helpful.

function applePayButtonClicked() {

     var chkresponse1=getCheckFinalAmount(); // this function returns the api response.

      var totalAmt = ((chkresponse.totals.sub_total / 100) + (chkresponse.totals.tax / 100) + tipamt).toFixed(2).toString();

}
ADyson
  • 57,178
  • 14
  • 51
  • 63
vignesh d
  • 235
  • 3
  • 6
  • 15
  • 2
    Impossible to answer without knowing what `getCheckFinalAmount` is doing. What does that return? A `Promise`? Is there a `callback` function that you can pass in? Take a look at https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest – mwilson Jan 31 '20 at 00:23

1 Answers1

1

You can use async/await. An async function will pause at each await expression until the promise is resolved. Also it's a good idea to catch any errors with a try catch block.

async function applePayButtonClicked() {
  try {
    const chkresponse1 = await getCheckFinalAmount();
    const totalAmt = ((chkresponse.totals.sub_total / 100) + (chkresponse.totals.tax       / 100) + tipamt).toFixed(2).toString();
  } catch (err) {
    console.log(err);
   //handle errors
  }
}

This solution assumes the expression following the await operator is'awaitable', meaning it is either a Promise or it can be converted to a resolved Promise. Here's what MDN says:

The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise.

If the Promise is rejected, the await expression throws the rejected value.

If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.

Community
  • 1
  • 1
LydiaHendriks
  • 1,290
  • 2
  • 11
  • 19
  • 1
    Worth noting that this would require `getCheckFinalAmount()` to be awaitable - we have no evidence whether it is or it isn't, since the OP didn't show it to us. So I think you need to make clear that your solution depends on an assumption. – ADyson Jan 31 '20 at 08:53