从 axios 返回数据而不是承诺

Eri*_*ric 0 javascript vue.js vuejs2

我使用 axios 对我的 json 文件进行了一次虚假的 api 调用。我从可以从中获取数据的函数中得到了一个承诺。但我不想要那样。我想从函数接收数据。

我现在的代码:products.js

export default {
    getAllProducts(axios) {
        return axios.get('fakedb.json').then(response => {
            return response.data;
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

视图文件:product.vue 文件

import productController from '~/data/controllers/product';
export default {
  data() {
    return {
      products: productController.getAllProducts(this.$axios).then(res => this.products = res)
    }
  },
}
Run Code Online (Sandbox Code Playgroud)

但这不是我想要实现的目标。我想要实现的是我的product.vue 文件中的这段代码:

import productController from '~/data/controllers/product';
export default {
  data() {
    return {
      products: productController.getAllProducts(this.$axios)
    }
  },
}
Run Code Online (Sandbox Code Playgroud)

我想接收数据而不必处理视图文件中的承诺。有什么解决方案如何在 products.js 文件中返回我的数据吗?

如果我像这样从 products.js 文件中正常返回,它就可以正常工作:

export default {
    getAllProducts(axios) {
        return [
          {
              "name": "Product1",
               "price": 9.75
          },
          {
              "name": "Product2",
              "price": 10.75
          }
        ]

    }
}
Run Code Online (Sandbox Code Playgroud)

但我希望它与 axios 一起使用

Joa*_*ild 5

既然你有一个 .vue 文件,我假设这是一个单页 vue 组件,对吧?因此您使用 vue-cli 或 webpack。因此,我假设您可以使用 async/await 语法。

从 axios 检索数据是异步的,因为你基本上无法知道它通过网络检索数据需要多长时间。而这种情况就是 async/await 的用途。

因此,使函数异步:

产品.js

export default {
    async getAllProducts(axios) {
        const response = await axios.get('fakedb.json');
        return response.data;
    }
}
Run Code Online (Sandbox Code Playgroud)

产品.vue:

import productController from '~/data/controllers/product';
export default {
  data() {
    return {
      products: [],
    };
  },
  async mounted: {
    this.products = await productController.getAllProducts(this.$axios);
  }
}
Run Code Online (Sandbox Code Playgroud)

我认为您不能使数据函数异步,因此返回一个空数据对象(我假设它是一个数组),然后使用钩子mounted检索数据。