javascript - 如何在 async/await 中实现 Promise 的 then ?

标签 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/

这根本行不通。日志在请求完成之前执行,即发生一些错误之后。请帮忙。

最佳答案

The log gets executed […] after some error has occured.

是的,在新的 todo 方法中,您捕获错误,然后返回 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)
  }
}

关于javascript - 如何在 async/await 中实现 Promise 的 then ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55060918/

相关文章:

javascript - Shadow DOM,使用目的

javascript - 这两个 async/await 函数有什么区别?

c# - 将二进制格式化程序与异步套接字一起使用

css - 如何覆盖 vuetify 样式?

javascript - 如何通过for循环将项目分成3列?

javascript - 使用 Bootstrap 使用 onclick 按钮在模式窗口中设置文本框值

javascript - 无法更新 JavaScript 全局变量

javascript - 在 Vue App 上使用 FieldValue 增加 Firestore 的值(value)

vue.js - 在子项 vueJS.2 之间切换 "active"类

javascript - 函数未在 javascript 中定义