繁体   English   中英

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

[英]How to implement Promise's then in async/await?

我有以下async/await方法:

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

getTodo() {
    this.todo()
}

现在,在async/await ,您如何知道请求已完成(200)? 在承诺中,我们简单地使用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/

就是行不通。 在请求完成之前(即发生某些错误之后)执行日志。 请帮忙。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM