Цепные обещания Vuex - PullRequest
       11

Цепные обещания Vuex

0 голосов
/ 28 января 2019

Мне нужно вызвать 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 голосов
/ 28 января 2019

Вы можете создать массив обещаний с .map() и разрешить с помощью .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);
    }
}
0 голосов
/ 28 января 2019

// 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-компоненте.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...