【问题标题】:How to implement Promise's then in async/await?那么如何在 async/await 中实现 Promise?
【发布时间】:2019-03-08 19:54:28
【问题描述】:

我有以下async/await 方法:

async todo() {
    const res = await axios.get('/todo')
}

getTodo() {
    this.todo()
}

现在,在async/await,你怎么知道请求已经完成(200)?在 Promises 中,我们只需使用 then:

// store/todo.js
todo() {
    const res = axios({
        method: 'GET',
        url: '/todo'
    })
    return res
}

// components/Todo.vue
getTodo() {
    this.todo().then(res => {
        console.log('Request Executed Successfully!')
    })
}

这非常有效,但是当我尝试在 getTodo 中添加 async/await 并执行如下操作时:

async todo() {
    try {
      const res = await axios.get('/todo')
      return res
    } catch(e) {
      console.log(e)
    }
}

async getTodo() {
  try {
    await this.todo()
    console.log('Request Completed')
  } catch(e) {
    console.log(e)
  }
}

演示:https://jsfiddle.net/jfn483ae/

它只是不起作用。日志在请求完成之前执行,即发生一些错误之后。请帮忙。

【问题讨论】:

标签: javascript asynchronous vue.js promise async-await


【解决方案1】:

发生一些错误后,日志会被执行 […]。

是的,在您的新 todo 方法中,您 catch 错误然后返回 undefined 作为正常结果。当您无法处理错误时,请不要使用try/catch,使用与您最初使用的代码相同的代码,并且当您await 它时,promise 将起作用:

todo() {
  return axios({
    method: 'GET',
    url: '/todo'
  })
}
async getTodo() {
  try {
    await this.todo()
    console.log('Request Completed')
  } catch(e) {
    console.log(e)
  }
}

【讨论】:

  • 似乎是更好的方法!谢谢!
猜你喜欢
  • 2021-11-05
  • 2016-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
  • 2017-10-10
相关资源
最近更新 更多