I need help implementing promise-based logic for asynchronous data fetching in VueJS.
Previously, I had the following logic:
if (influencer.suggested?.length && url.length) {
const [ interactions, suggested_ids ] = await Promise.all([
$axios.$get(url),
store.dispatch('influencers/FETCH_SET', influencer.suggested),
]);
return ({
interactions,
suggested_ids,
});
}
However, the if
conditions were dependent on each other, and I want them to be independent so that one can execute even if the other is false.
Here is my updated implementation:
if (store.getters['user/is_band']) {
url = '/band/history/?influencer_id=' + influencer.id;
}
const interactionPromise = new Promise((resolve, reject) => {
if (url.length) {
resolve($axios.$get(url));
} else {
reject();
}
});
const suggestionPromise = new Promise((resolve, reject) => {
if (influencer.suggested?.length) {
resolve(store.dispatch('influencers/FETCH_SET', influencer.suggested));
} else {
reject();
}
});
const [interactions, suggested_ids] = await Promise.all([
interactionPromise.catch(error => console.log(error)),
suggestionPromise.catch(error => console.log(error)),
]);
return ({
interactions,
suggested_ids,
});
It appears that when one of the promises is rejected, it should failover to the other one, but this doesn't seem to be happening.
In addition, if store.getters['user/is_band']
is false, the app crashes. How can I prevent this from happening?
Any assistance with executing Promise.all
without crashing if one of the promises is rejected would be greatly appreciated!