【问题标题】:Can't return Promise value outside of Axios call无法在 Axios 调用之外返回 Promise 值
【发布时间】:2021-09-19 16:56:11
【问题描述】:

我想让我的值返回到外面,以便在我的 vue 端显示它,但我不明白..

我在状态文件中的 getter (vueX)

getTotalPrice: (state) => {
        var totalPrice = axios.get("http://" + url + "/meals/")
            .then((meals) => {
                var price = 10

                //ignore this for simplicity ---------------
                state.all_orders.forEach((order) => {
                    price += order.quantity * meals.data.find(elem => elem.id === order.meal_id).price
                })
                //------------------------------------------


                return price
            })

        return totalPrice
    }

它应该返回 10 作为总价,我在控制台中得到它,但仍然在 vue 端得到 [object Promise]

感谢您的帮助!

【问题讨论】:

    标签: vue.js promise axios vuex


    【解决方案1】:

    这可能是因为在 promise 被解决之前,您试图返回 totalPrice,它只是一个未解决的 promise。

    我坚持你在这种情况下使用 async-await

    getTotalPrice: async (state) => { // change added
            var totalPrice = await axios.get("http://" + url + "/meals/") //change added
                .then((meals) => {
                    var price = 10;
                    //ignore this for simplicity ---------------
                    state.all_orders.forEach((order) => {
                        price += order.quantity * meals.data.find(elem => elem.id === order.meal_id).price
                    })
                    //------------------------------------------
                    return price;
                })
    
            return totalPrice;
        }
    

    【讨论】:

      【解决方案2】:

      Vuex 允许我们在 store 中定义“getter”。您可以将它们视为商店的计算属性。与计算属性一样,getter 的结果基于其依赖项进行缓存,并且仅在其某些依赖项发生更改时才会重新评估。 vuex manual

      Getter 不能包含异步功能。您应该在 vuex 模块的操作部分从服务器获取数据。将 axios 部分移到那里并存储带有突变的数据,然后使用 getter 计算总价格。

      【讨论】:

        猜你喜欢
        • 2016-12-27
        • 2019-05-08
        • 1970-01-01
        • 2022-07-06
        • 2020-06-02
        • 2020-07-31
        • 2020-12-02
        • 2019-02-13
        • 2021-07-23
        相关资源
        最近更新 更多