javascript - 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
}
解决方案
您应该在异步函数中调用 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
})
推荐阅读
- android - 如何在android中强制KaTexView对齐
- amazon-web-services - 允许 EC2 实例访问附加了拒绝策略的存储桶
- vue.js - Shopware 6 中 Vue.js 店面中的 CSRF 令牌
- java - REST 服务的 UnsatisfiedDependencyException
- postgresql - 将 Postgres 表备份到不同的服务器上
- javascript - 如何在 React 中制作正确的 JSON 循环
- bash - Git 通过 bash 脚本推送到各种存储库
- typescript - 如何将 DOM 声明为可能未定义
- polymer - 聚合物元素镭-datagrid-column,我需要自定义图标,其标题内有链接
- php - Laravel 上的搜索查询功能