链接承诺Vuex

时间:2019-01-28 10:14:28

标签: javascript vue.js vuex

我必须为一组端点调用一个API,以后再用它们从第二个API提取数据。

// Raise isLoadign flag
    this.$store.commit('isLoading', true);
    // Initial data fetch
    this.$store.dispatch('getAvailableProductGroups').then(() => {
      // Call API for every available product
      for(let group of this.$store.state.availableProductGroups) {
        // Check if it's the last API call
        this.$store.dispatch('getProductsData', group).then((response) => {
          // // Reset isLoading flag
          // this.$store.commit('isLoading', false);
          });
        }
    }); 

当我从第一个API请求端点列表时,我设置了isLoading标志,但是我不知道如何检查最后一个承诺何时得到解决,以便我可以重置标志。

2 个答案:

答案 0 :(得分:0)

// Raise isLoadign flag
this.$store.commit('isLoading', true);
// Initial data fetch
this.$store.dispatch('getAvailableProductGroups')
  .then(() => {
    // Call API for every available product
    return Promise.all(this.$store.state.availableProductGroups.map(group => {
      // Check if it's the last API call
      return this.$store.dispatch('getProductsData', group);
    });
  })
  .then((allResults) => {
    this.$store.commit('isLoading', false);
  });

但是应该在商店操作中,而不是在vue组件中。

答案 1 :(得分:0)

您可以使用.map()创建一个promise数组,并使用.all()进行解决

没有异步/等待状态

this.$store.commit('isLoading', true);
this.$store.dispatch('getAvailableProductGroups').then(() => {
    // Create an array of promises
    const groupPromises = this.$store.state.availableProductGroups.map(group =>  this.$store.dispatch('getProductsData', group))
    Promise.all(groupPromises).then( values => {
        // array of promise results
        console.log(values);
        this.$store.commit('isLoading', false);
    });
});

使用异步/等待

async function doSomething() {
    try {
        this.$store.commit('isLoading', true);
        await this.$store.dispatch('getAvailableProductGroups')
        // Create an array of promises
        const groupPromises = this.$store.state.availableProductGroups.map(group =>  this.$store.dispatch('getProductsData', group))
        // Wait to resolve all promises
        const arrayOfValues = await Promise.all(groupPromises);
        this.$store.commit('isLoading', false);
    } catch(err) {
        console.log(err);
    }
}