Nuxt Js asyncData 返回值行为异常。

Nuxt Js asyncData returning value acting strange.

我正在做一个 nuxt js/vue js 项目。在其中我必须调用多个 REST API。在页面组件中,我调用 asyncData() nuxt js API 来调用 REST api。

import { getCategories } from '~/api'
import { getProducts } from '~/api'


export default {

data() {
  return {

  }
},`



asyncData ({ req, params }) {
 //-----------------PART 1-----------------------------
    // var res1 = getCategories()
    // var res2 = getProducts()

    // return {
    //   res1,
    //   res2
    // }
//-----------------PART 2-----------------------------
    // return getCategories()
    // return getProducts()


//----------------------------------------------
      },



created() {

    if(typeof(Storage) !== "undefined"){

      if(!localStorage.getItem("cityName")){
        this.$router.push('/')
      }

    } else{
      console.log('This browser does not support local storage')
    }

    this.$store.dispatch('initFilters')


    this.$store.dispatch('initCategories', this.categories) 

   //NOTICE HERE
   // console.log(this.allProducts) //This one works on single return
   // console.log(this.res1.allProducts) //This doesnot work on object return

  },

}

当我尝试 return getCategories()return getProducts()(第 2 部分代码)有效并且 return 我想要的对象结果。

但是因为我需要这两个对象,所以我尝试将它们放在一个对象中并 return 它们(第 1 部分)然后通过 console.log(this.res1.allProducts) 我没有得到想要的对象。

这是API代码

import axios from 'axios'
const API_ROOT = 'http://deligram.mg/rest/'
const API_VERSION = 'V1'
const MAGENTO_STORE = 'default'
const API_BASE = API_ROOT + '/' + MAGENTO_STORE + '/' + API_VERSION + '/'

const apiUrl = (path) => {
  return API_BASE + path
}

const apiGet = (path) => {
  return axios.get(apiUrl(path))
}

export function getCategories () {
  return apiGet('categories')
  .then((res) => {
    return { categories: res.data }
  })
}

export function getProducts () {
  return apiGet('products?searchCriteria%5BcurrentPage%5D=10')
  .then((res) => {
    return { allProducts: res.data }
  })
}

谁能告诉我我做错了什么?或者任何人都可以提出一种替代方法来获得单个 return 中的两个对象吗?

我假设您的 API 方法 return 是一个 Promise。您应该使用 Promise.all 等待两个承诺都得到解决,然后 return one 包含 all 数据的对象应该设置:

var res1 = getCategories()
var res2 = getProducts()
return Promise.all(re1, res2).then(function ([data1, data2]) {
 return Object.assign({}, data1, data2)
})

生成的对象将如下所示:

{
  categories: [ /* data from getCategories() */]
  allProducts: [ /* data from getProducts () */ ]
}