【问题标题】:Await JS function is slowAwait JS 函数很慢
【发布时间】:2022-06-10 20:35:56
【问题描述】:

我正在构建一个购物应用程序,我正在编写一个 JS 函数,单击该函数可以通过 API 从我的后端数据库中检索凭证。我注意到当我使用 await 时,它有时会很慢(大约 300 毫秒),但时间会有所不同。我可以确认它不是数据库操作,因为我已经对其进行了计时,并且在 await 函数中代码似乎很慢。我必须等待获取 API 响应以检查有效的优惠券代码。

有什么办法可以改进这段代码吗?

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


  });

【问题讨论】:

  • 那么慢是什么?取物?加工?您需要进一步调试它并找出瓶颈所在。
  • 300ms 对于网络操作来说并不慢,或者至少不是很慢。

标签: javascript jquery


猜你喜欢
  • 2018-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
  • 2021-05-02
  • 2018-12-26
  • 2014-01-20
相关资源
最近更新 更多