【问题标题】:How to write function without using async/await?如何在不使用 async/await 的情况下编写函数?
【发布时间】:2018-12-04 11:54:26
【问题描述】:

我有以下功能来自:https://github.com/anaida07/MEVN-boilerplate/blob/master/client/src/components/EditPost.vue

methods: {
  async getPost () {
    const response = await PostsService.getPost({
      id: this.$route.params.id
    })
    this.title = response.data.title
    this.description = response.data.description
  // this.$router.push({ name: 'Posts' })
},

我正在学习 MEVN。我想知道是否有在不使用 async/await 的情况下编写相同的函数。我目前想出了以下几点:

methods: {
  getPost () {
    const response = PostsService
    .getPost({
      id: this.$route.params.id
    })
    this.title = response.data.title
    this.description = response.data.description

   //this.$router.push({ name: 'Posts' })
},

但我在控制台日志中收到错误消息:挂载钩子错误:“TypeError: response.data is undefined”。任何帮助将不胜感激。

【问题讨论】:

  • 是你不想要async-await语法的原因吗?
  • 由于某种原因它不适用于我的 webpack 版本

标签: express vue.js async-await


【解决方案1】:

它看起来像 PostsService 扩展了 axios,所以你可以将它用作一个承诺:

methods: {
  getPost () {
    PostsService
      .getPost({
        id: this.$route.params.id
      })
      .then(({data}) => {
        this.title = data.title
        this.description = data.description
        this.$router.push({ name: 'Posts' })
      }

},

您的错误的原因是 response = PostsService.getPosts() 实际上并没有用数据填充响应变量。它必须先运行查询,然后您可以在.then() 的回调中访问它

【讨论】:

  • 我同意杰夫的观点。 response 未定义,因为 PostsService.getPost() 是一个异步请求,您必须等待它解析(或拒绝)才能访问响应内容。对于此请求引发的错误,您可以在 then() 案例之后使用 catch() 块捕获它们。
  • 谢谢,这是一个快速修复!
猜你喜欢
  • 2019-12-04
  • 2022-11-15
  • 2019-10-08
  • 1970-01-01
  • 2018-03-24
  • 1970-01-01
  • 2022-08-06
  • 2017-09-08
  • 1970-01-01
相关资源
最近更新 更多