1 回答

TA貢獻(xiàn)1878條經(jīng)驗(yàn) 獲得超4個贊
不幸的是,在拋出錯誤后,promise 不會對數(shù)據(jù)值進(jìn)行curry。您已經(jīng)在使用一個臨時變量,為什么不使用兩個呢?:
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 語句混合使用,我會持謹(jǐn)慎態(tài)度。如果populartimes是異步函數(shù),您的代碼將按預(yù)期工作,但是如果它是返回承諾的普通函數(shù),則您的代碼將不會處理拋出錯誤的情況(返回承諾的函數(shù)可以拒絕承諾或拋出錯誤)。
僅使用await,try/catch您的代碼將相當(dāng)于:
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.';
}
添加回答
舉報