【问题标题】:Vue - call async action only after first one has finishedVue - 只有在第一个完成后才调用异步操作
【发布时间】:2018-03-30 22:43:40
【问题描述】:

我需要从我的组件内部调用 2 个操作,但第二个操作应该在第一个操作 100% 完成它的工作后才开始。

我正在尝试,但它不起作用

mounted() {
    this.$store.dispatch('coinModule/loadApiCoins')
        .then(() => {
            this.$store.dispatch('coinModule/loadUserCoins')
        })
        .catch(error => {
            console.log(error)
        });
},

这两个动作是这些

    loadApiCoins({ commit, dispatch, rootGetters }) {
        Vue.axios({
                method: 'get',
                url: 'https://api.coinmarketcap.com/v1/ticker/',
                transformRequest: [(data, headers) => {
                    delete headers.common.Authorization
                    return data
                }]
            })
            .then(response => { commit('SET_API_COINS', response.data) })
            .catch(error => { console.log(error) })
    },

    loadUserCoins({ commit, dispatch, rootGetters }) {
        Vue.axios.get('http://127.0.0.1:8000/api/coins/')
            .then(response => {
                commit('SET_USER_COINS', response.data)
                commit('SET_USER_PORTFOLIO_OVERVIEW')
            })
            .catch(error => { console.log(error) })
    }

这些应该是相反的。 Screen of my network tab

【问题讨论】:

    标签: vuejs2 vue-component vue-router vuex


    【解决方案1】:

    当您调度一个动作时,默认情况下它没有then 回调。只有当操作返回Promise 时才会出现这种情况。您的axios.get 调用应该返回Promise,但您并没有在您的操作中返回它。您应该简单地返回它,然后 then 回调将在您的 mounted 钩子中触发。

    loadApiCoins({ commit, dispatch, rootGetters }) {
      return Vue.axios({
        method: 'get',
        url: 'https://api.coinmarketcap.com/v1/ticker/',
        transformRequest: [(data, headers) => {
          delete headers.common.Authorization
          return data
        }]
      })
      .then(response => { commit('SET_API_COINS', response.data) })
      .catch(error => { console.log(error) })
    },
    

    【讨论】:

    • 你的代码和我的一样。我如何用 axios 返回一个承诺?我认为“.then()”是承诺...?
    • 我的错。我刚刚看到你在任何东西之前添加了“return”。就是这样了?我很困惑..
    • 对。假设您将dispatch 调用的返回值存储在mounted 钩子中,例如let promise = this.$store.dispatch('coinModule/loadApiCoins')。在您的代码中,loadApiCoins 操作不会返回任何内容,因此 promise 将是 undefined 并且 promise.then(() => { }) 将导致错误。这就是this.$store.dispatch('coinModule/loadApiCoins').then(() => { }) 不起作用的原因。调度调用的结果值为undefined。您需要从 Vue.axios 调用中显式返回结果 Promise
    • 我还是一头雾水。如果我尝试记录组件的响应,它仍然是未定义的,所以我猜我并没有真正返回它,但代码现在按预期工作.. this.$store.dispatch('coins/loadApiCoins') .then(响应 => { console.log(response) })
    • 我不确定您所说的“记录来自组件的响应”是什么意思。如果您像我展示的那样在dispatch 方法中返回axios 调用,那么console.log(this.$store.dispatch('coinModule/loadApiCoins')) 应该在控制台中记录一个Promise 对象。我认为您可能还会使用then 回调记录dispatch 调用。由于then 方法不返回任何内容,console.log(this.$store.dispatch('...').then(() => {})) 将在控制台中记录undefined。这是意料之中的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 2018-03-09
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多