I am building a shopping app and I am writing a JS function that on click retrieves the vouchers from my backend DB via an API. I notice when I use await, It is pretty slow sometimes (about 300 ms) but the time varies. To explain End to end operation from when the button is clicked its 300 ms. The database fetch operation is about 80 ms. So that means on the JS end its about 220ms. I believe the await function is slowing it down.
I have to await to get the API response to check for a valid coupon code.
Is there any way to improve this code?
// coupon
$('.coupon').click(function() {
(async () => {
var startTime = performance.now();
alert('Run some function here');
var couponfield = document.getElementById("couponfield")
console.log("TEST")
console.log(couponfield.value)
const rawResponse = await fetch(`/getcoupons?couponcode=` + couponfield.value, {
method: 'GET'
});
response = await rawResponse.text()
console.log(response)
jsonarray = JSON.parse(response)
console.log(jsonarray.DISCOUNT)
couponflag = couponfield.value
console.log(jsonarray)
if (couponfield.value===jsonarray.DISCOUNT_CODE){
console.log("after now example")
for (i in cart){
cart[i].couponcode = couponfield.value;
cart[i].discount = jsonarray.DISCOUNT/100;
cart[i].oldTotal = cart[i].price * cart[i].count;
cart[i].total = cart[i].price * cart[i].count * (1-cart[i].discount);
}
}
/*
for (let i=0; i<jsonarray.length; i++){
if (jsonarray[i]===couponfield.value){
console.log("equal")
couponflag = couponfield.value
shoppingCart.addCouponCart(couponfield);
}
}
*/
displayCart();
var endTime = performance.now();
var totalTime=endTime-startTime;// time took to run in milliseconds
alert('Total time:'+totalTime +'ms');
})();
});