的javascript - 如何尝试赶上一个异步函数

问题描述:

我有一个使用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函数中的网络请求封装起来,还是有办法在函数调用中执行?

+0

因为赶上这样的只对承诺。 – azurinko

+0

@azurinko一个异步函数*是一个承诺。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function:“当一个异步函数被调用时,它会返回一个Promise。当异步函数返回一个值时,Promise将会用返回的值解析,当异步函数抛出异常或某个值时,Promise将被抛出的值拒绝。“ – TKoL

+0

是的,返回值,但是.catch和.then,你必须返回一个PROMISE。 – azurinko

您可以使用正常的try-catch块或承诺特征.catch()

Here's a writeup on it

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 []; 
    } 
} 
+0

嗯,当我把试穿/ catch语句放入loadAvailableDates函数中,我仍然在控制台中收到错误,并阻止函数执行?但是当我把try catch放在实际的函数调用中时,它正确执行。 –

+0

@MihaŠušteršič这真的很奇怪。老实说,我自己并没有太多练习使用'async',我仍在承诺(等待当前版本的Node支持异步等待)。我对这种情况的原因没有任何了解。但祝你兄弟好运。 – TKoL

使用定期尝试捕捉错误而不是.catch()

var dates; 
try { 
    dates = await this.props.uiStore 
     .loadAvailableDates(endDate, startDate, managedParcel.bounds) 
} catch { 
    dates = []; 
} 
return dates; 

你需要返回一个承诺......

Check out advenced example here with .catch