2017-10-20 97 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