【问题标题】:await - catch error - UnhandledPromiseRejectionWarning等待 - 捕获错误 - UnhandledPromiseRejectionWarning
【发布时间】:2018-04-01 15:11:36
【问题描述】:

我明白了

 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 函数中捕获错误吗?

【问题讨论】:

    标签: es6-promise ecmascript-2017


    【解决方案1】:

    您将 async/await 与 Promise 混为一谈。在api.js 中,不需要使用 async 关键字。 async 关键字使得你从函数返回的任何东西都被包装在一个你不需要的 Promise 中,因为 axios.get 已经返回了一个 Promise。

    另外,你忘了实际从 Axios 返回承诺,你的 request 函数只是返回 undefined

    最后,您不必从 thencatch 方法返回 Promise,只需返回一个值或抛出错误。

    如果你像这样重写函数,它应该可以按预期工作:

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

    【讨论】:

    • 谢谢,我刚刚注意到我忘记了返回函数 - 好的,我想我明白了,我在一个有点没用的承诺中返回一个承诺
    猜你喜欢
    • 2019-05-02
    • 2017-11-09
    • 2019-02-11
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 2018-07-19
    • 2021-03-08
    • 2019-03-19
    相关资源
    最近更新 更多