我有一个使用axios发出网络请求的函数:
Layout = null
然后我在另一个代码块中调用此函数:
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)
但它不起作用。
我是否需要将网络请求包装在try / catch块中的const dates = await this.props.uiStore
.loadAvailableDates(endDate, startDate, managedParcel.bounds)
.catch(e => return [])
函数中,或者有没有办法在函数调用中执行此操作?
答案 0 :(得分:4)
您可以使用普通的try-catch块或promise-feature .catch()
let dates = [];
try {
dates = await this.props.uiStore
.loadAvailableDates(endDate, startDate, managedParcel.bounds)
} catch (e) {
dates = [];
}
return dates;
- 编辑
也试试这个:
async loadAvailableDates(startDate, endDate, bounds) {
try {
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;
} catch (e) {
return [];
}
}
答案 1 :(得分:0)
使用常规try catch来捕获错误而不是.catch()
var dates;
try {
dates = await this.props.uiStore
.loadAvailableDates(endDate, startDate, managedParcel.bounds)
} catch {
dates = [];
}
return dates;
答案 2 :(得分:0)
你需要回复承诺......