如何允许条件承诺触发/不触发并仍然正确解决?
让我解释一下背景。我有三个要查找的值。起初我做了
var CustomerReceived = myAjaxLibCall("Customer", "ID", report.CustomerID);
var VehicleReceived = myAjaxLibCall("Vehicle", "ID", report.VehicleID);
var DealerReceived = myAjaxLibCall("Dealer", "ID", report.DealerID);
$.when(CustomerReceived,
VehicleReceived,
DealerReceived)
.then((Customer,
Vehicle,
Dealer) => {
//do some code here
});
这很好用。但是,AJAX调用很慢并且需要花费很多时间。当用户在创建新报告后到达此点时,他们已经填充了每个项目的列表,这意味着我可以这样做
var Customer = customerList.findbyID(report.CustomerID);
var Vehicle = vehicleList.findbyID(report.VehicleID);
var Dealer = dealerList.findbyID(report.DealerID);
//do some code here
然后,事实证明,这些列表中的每一个都可能被填充,而且可能没有,有时一个或两个是,而其他则不是。理想情况下,如果相应的本地列表不存在,我只想执行每个ajax调用。
但这样做的最佳方法是什么?这是我尝试过的,但它不起作用:
var CustomerReceived = customerList.length === 0
? myAjaxLibCall("Customer", "ID", report.CustomerID)
: customerList.findbyID(report.CustomerID);
var VehicleReceived = vehicleList.length === 0
? myAjaxLibCall("Vehicle", "ID", report.VehicleID)
: vehicleList.findbyID(report.VehicleID);
var DealerReceived = dealerList.length === 0
? myAjaxLibCall("Dealer", "ID", report.DealerID)
: dealerList.findbyID(report.DealerID);
$.when(CustomerReceived,
VehicleReceived,
DealerReceived)
.then((Customer,
Vehicle,
Dealer) => {
//do some code here
});
答案 0 :(得分:1)
您可以使用await关键字:
async function someStuff()
{
var CustomerReceived = customerList.length === 0
? myAjaxLibCall("Customer", "ID", report.CustomerID)
: customerList.findbyID(report.CustomerID);
var VehicleReceived = vehicleList.length === 0
? myAjaxLibCall("Vehicle", "ID", report.VehicleID)
: vehicleList.findbyID(report.VehicleID);
var DealerReceived = dealerList.length === 0
? myAjaxLibCall("Dealer", "ID", report.DealerID)
: dealerList.findbyID(report.DealerID);
const Customer = await CustomerReceived;
const Vehicle = await VehicleReceived;
const Dealer = await DealerReceived;
//do some code here
}
根据MDN:
如果await运算符后面的表达式的值不是a 承诺,它已转换为已解决的承诺。
如果您不想使用async关键字,可以使用Promise.all(),但需要将promises / functions存储到数组中
var CustomerReceived = customerList.length === 0
? myAjaxLibCall("Customer", "ID", report.CustomerID)
: customerList.findbyID(report.CustomerID);
var VehicleReceived = vehicleList.length === 0
? myAjaxLibCall("Vehicle", "ID", report.VehicleID)
: vehicleList.findbyID(report.VehicleID);
var DealerReceived = dealerList.length === 0
? myAjaxLibCall("Dealer", "ID", report.DealerID)
: dealerList.findbyID(report.DealerID);
Promise.all([ CustomerReceived, VehicleReceived, DealerReceived ])
.then(([ Customer, Vehicle, Dealer ]) => {
//do some code here
});
仍然根据MDN:
如果所有传入的承诺都履行或不承诺,那么 Promise.all返回的promise是异步完成的。在所有 例如,返回的promise通过包含all的数组来实现 迭代的值作为参数传递(也是非承诺 值强>)。