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();
}