等待 - 捕获错误 - UnhandledPromiseRejectionWarning

await - catch error - 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 函数的错误吗?

您混淆了 async/await 和承诺。在api.js中,不需要使用async关键字。 async 关键字使得你从函数 return 中得到的任何东西都被包裹在一个你不需要的承诺中,因为 axios.getreturn已经是承诺了。

此外,您实际上忘记了 return 来自 Axios 的承诺,您的 request 函数只是 returns undefined.

最后,您不必 return 来自 thencatch 方法的承诺,只需 return一个值,否则抛出错误。

如果您像这样重写函数,它应该会按预期工作:

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