[英]Chaining promises 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標志,但是我不知道如何檢查何時最后一個承諾已解決,以便我可以重置標志。
// 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組件中。
您可以使用.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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.