我有一個使用Axios公司進行網絡請求的功能:的javascript - 如何嘗試趕上一個異步函數
async loadAvailableDates(startDate, endDate, bounds) {
const polygon = this.getDatePolygon(bounds);
let indexUrl = `${this.baseUrl}index/v2/search`;
var url = `${indexUrl}?timefrom=${startDate}&timeto=${endDate}T23:59:59&&maxcount=31`;
const res = await this.httpClient.post(url, polygon);
const availableDates = [];
res.data.tiles.map(tile => {
availableDates.push({
date: tile.sensingTime.split("T")[0],
cloudCoverage: tile.cloudCoverPercentage
});
});
return availableDates;
}
然後我調用這個函數在另一個代碼塊:
const dates = await this.props.uiStore
.loadAvailableDates(endDate, startDate, managedParcel.bounds)
現在我想在這個函數中實現錯誤處理,以防網絡請求失敗(而不是我想返回一個空數組的錯誤)。
我試着這樣做:
const dates = await this.props.uiStore
.loadAvailableDates(endDate, startDate, managedParcel.bounds)
.catch(e => return [])
但它不工作。
是否需要在try/catch塊中將loadAvailableDates
函數中的網絡請求封裝起來,還是有辦法在函數調用中執行?
因爲趕上這樣的只對承諾。 – azurinko
@azurinko一個異步函數*是一個承諾。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function:「當一個異步函數被調用時,它會返回一個Promise。當異步函數返回一個值時,Promise將會用返回的值解析,當異步函數拋出異常或某個值時,Promise將被拋出的值拒絕。「 – TKoL
是的,返回值,但是.catch和.then,你必須返回一個PROMISE。 – azurinko