如何在异步/等待中实现Promise的呢?

时间:2019-03-08 10:08:18

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

我有以下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/

它根本不起作用。在请求完成之前(即发生某些错误之后)执行日志。请帮忙。

1 个答案:

答案 0 :(得分:2)

  

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

是的,在新的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)
  }
}