首页 > 解决方案 > Javascript: How do I wait until async response has required data before continuing

问题描述

How do I wait until the async response has required data before continuing?

I have a few async functions that apply a discount and fetch the order that SHOULD contain the order with a discount applied. The problem is sometimes the discount is applied and order call does not contain the discounts in the response. (I am guessing the process takes a few seconds for the discount to reflect on the order). What is the best way to ensure the required data is present before moving on to the code? I tried below, but no luck. Thanks in advance.

             //Apply Discount
             await this.attemptDiscount(
                payload
              );

              const order = await this.ordersService.getOrder(
                orderId
              );

              //Required condition
              if (
                order.hasOwnProperty("discounts") &&
                order.discounts[0].name ===
                  "Exclusive Discount"
              ) {
                // Proceed with code
              }

标签: javascriptangulartypescriptasynchronous

解决方案


您应该在异步函数中调用 await

async applyDiscountAndOrderItem(payload,orderId){


 var discount =  await this.attemptDiscount(
                payload
              );

              const order = await this.ordersService.getOrder(
                orderId
              );

              //Required condition
              if (
                order.hasOwnProperty("discounts") &&
                order.discounts[0].name ===
                  "Exclusive Discount"
              ) {
                // Proceed with code
              }
}

你可以调用 tis 函数

applyDiscountAndOrderItem(payload,orderId).then((response)=>{


success call back

},(err)=>{
eror call back
})

推荐阅读