2017-10-20 88 views
0

我越來越等待 - catch錯誤 - UnhandledPromiseRejectionWarning

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 44): Error: fail 

main.js

import { request } from './api' 

async getData({ commit, state }, ids){ 
    try { 
    var x = await request(ids) 
    commit('getData', x.data) 
    } catch (e) { 
    console.log('request failed get',e.code,e.errno) 
    } 
} 

api.js

export async function request(type,url,ids){ 
    axios.get('localhost/data') 
    .then(function (response) { 
     return Promise.resolve(response.data) 
    }) 
    .catch(function (e) { 
    return Promise.reject(new Error('fail')) 
    }) 
} 

我如何處理的承諾拒絕? try catch塊不應該從await函數中捕獲錯誤嗎?

回答

1

你正在混淆異步/等待與承諾。在api.js中,不需要使用異步關鍵字。 async關鍵字使得它可以讓您從函數返回的任何內容都包含在您不需要的承諾中,因爲axios.get已經返回承諾。

另外,您忘了實際退還Axios的承諾,您的request函數剛剛返回undefined

最後,您不必返回從承諾再方法,只返回一個值,或拋出一個錯誤。

如果重寫功能,這樣就應該按預期工作:

export function request(type,url,ids){ 
    return axios.get('localhost/data') 
    .then(function (response) { 
     return response.data 
    }) 
    .catch(function (e) { 
     throw new Error('fail') 
    }) 
} 
+0

感謝,我只注意到我忘了復位功能 - 好吧,我想我明白了,我回一個承諾中承諾這是沒用的 – user345234674567