首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >连锁承诺

连锁承诺
EN

Stack Overflow用户
提问于 2019-01-28 10:14:28
回答 2查看 543关注 0票数 0

我必须为一个端点数组调用一个API,这些端点后来用于从第二个API中获取数据。

代码语言:javascript
复制
// 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标志,但我不知道如何检查最后的承诺何时已经解决,以便能够重置标志。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-01-28 11:30:00

代码语言:javascript
复制
// 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组件中的。

票数 0
EN

Stack Overflow用户

发布于 2019-01-28 11:33:47

您可以使用.map()创建一系列承诺,用.all()解决问题。

无异步/等待

代码语言:javascript
复制
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);
    });
});

带有异步/等待

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54399730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档