我必须为一个端点数组调用一个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标志,但我不知道如何检查最后的承诺何时已经解决,以便能够重置标志。
发布于 2019-01-28 11:30:00
// 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组件中的。
发布于 2019-01-28 11:33:47
您可以使用.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);
}
}https://stackoverflow.com/questions/54399730
复制相似问题