1 回答
TA贡献1878条经验 获得超4个赞
不幸的是,在抛出错误后,promise 不会对数据值进行curry。您已经在使用一个临时变量,为什么不使用两个呢?:
var temp;
var out!: any;
await populartimes(markers[i].placeID)
.then(value => {
out = value;
temp = 'Currently ' + out.now.currently + ' full.';
})
.catch(() => {
temp = 'Live data is not currently available. Historically, ' + markers[i].name + ' would be ' + out.now.usually + ' full.';
})
.catch(() => {
temp = 'There is currently no data available.';
});
但是,对于将 promise 处理与 await 语句混合使用,我会持谨慎态度。如果populartimes是异步函数,您的代码将按预期工作,但是如果它是返回承诺的普通函数,则您的代码将不会处理抛出错误的情况(返回承诺的函数可以拒绝承诺或抛出错误)。
仅使用await,try/catch您的代码将相当于:
var temp;
try {
var out = await populartimes(markers[i].placeID);
try {
temp = 'Currently ' + out.now.currently + ' full.';
} catch {
temp = 'Live data is not currently available. Historically, ' + markers[i].name + ' would be ' + out.now.usually + ' full.';
}
} catch {
temp = 'There is currently no data available.';
}
添加回答
举报