2017-10-06 62 views
0

我有一個使用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

回答

4

您可以使用正常的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

0

使用定期嘗試捕捉錯誤而不是.catch()

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