【问题标题】:Return axios response from async service (Vue + Nuxt)从异步服务返回 axios 响应(Vue + Nuxt)
【发布时间】:2021-01-24 17:19:24
【问题描述】:

我正在尝试从服务的 axios 响应返回数据,但我将始终从服务undefined 接收数据,但在服务内部我有数据。你能告诉我我做错了什么吗?

这是我的服务的样子:

import axios from 'axios';

export default {
  async fetchById (articleId) {
    await axios.post('/api/article', { id: articleId })
      .then(function (response) {
        console.log('axios', response) // valid response
        return response.data
      })
      .catch(function (e) {
        console.error('error', e);
      });
  }
}

还有我在组件中的用法:

async created () {
  const article = await articleService.fetchById('12345')
  console.log('article', article) // there I have undefined
}

【问题讨论】:

    标签: javascript vue.js axios nuxt.js


    【解决方案1】:

    在第一个示例中,您只能使用 async/await 然后返回结果:

    import axios from 'axios';
    
    export default {
    
      async fetchById (articleId) {
         try{
         const  response= await axios.post('/api/article', { id: articleId })
            return response.data
          }catch(e){
            console.error('error', e);
            return null;
          };
      }
    }
    

    【讨论】:

      【解决方案2】:

      您缺少退货声明

      import axios from 'axios';
      
      export default {
        async fetchById (articleId) {
          // Missing `return` in the next line
          return await axios.post('/api/article', { id: articleId })
            .then(function (response) {
              console.log('axios', response) // valid response
              return response.data
            })
            .catch(function (e) {
              console.error('error', e);
            });
        }
      }
      

      我鼓励你开始使用 TypeScript,这些错误可以通过正确的函数类型轻松避免。

      【讨论】:

      • 好,我同意你的观点 typescript 节省了调试时间
      • 谢谢,我不知道内部返回不是从函数返回值
      【解决方案3】:

      您可以使用 callback() 函数。这是当您将函数作为参数传递给现有函数时,该函数将在您的 axios 调用完成后执行。以下是它如何与您的代码一起使用:

      async fetchById (articleId) {
        await axios.post('/api/article', { id: articleId })
        .then(function (response) {
          console.log('axios', response) // valid response
          callback(response.data)
        })
        .catch(function (e) {
          console.error('error', e);
        });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-09
        • 2019-07-30
        • 1970-01-01
        • 1970-01-01
        • 2021-01-24
        • 1970-01-01
        • 2020-02-06
        相关资源
        最近更新 更多