Troubleshooting VueJS Promise.all Problem

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!

Answer №1

My approach to tackling this issue would be as follows:

// Initializing variables for later assignment
let interactions, suggested_ids;

// If the user is a band
if (store.getters['user/is_band']) {
    try {
        interactions = await $axios.$get('/band/history/?influencer_id=' + influencer.id);
    } catch (ex) {
        // Handling rejected Promise
    }
}

// Check if there are suggested influencers for the current influencer
if (influencer.suggested?.length) {
    try {
        suggested_ids = await store.dispatch('influencers/FETCH_SET', influencer.suggested);
    } catch (ex) {
        // Handling rejected Promise
    }
}

return {
    interactions,
    suggested_ids
};

In my opinion, using Promise.all may not be the most suitable solution in this case because it combines all Promises and provides a single resolve or reject state. This means that if any one Promise is rejected, the entire Promise.all will be rejected.

By dividing the promises like this, you have more control over how each promise is handled independently.

Answer №2

Triggering Promise.all will result in rejection if any of the elements are rejected, but this behavior can be modified by handling potential rejections.

(async function() {

const p1 = new Promise((resolve, reject) => { 
  setTimeout(() => resolve('p1_delayed_resolution'), 1000); 
}); 

const p2 = new Promise((resolve, reject) => {
  reject('p2_immediate_rejection');
});


const [p1Result, p2Result] = await Promise.all([
  p1.catch(error => error ),
  p2.catch(error => error ),
]);

console.log(p1Result, p2Result)
}());

For your scenario, a similar implementation would look like:

const [ interactions, suggested_ids ] = await Promise.all([
        $axios.$get(url).catch(e => e),
        store.dispatch('influencers/FETCH_SET', influencer.suggested).catch(e => e),
    ]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I often find myself frustrated while using Next.js because the console automatically clears itself, making it difficult for me

I am facing an issue with my form in the Next.js app. Here is how it is defined: <form onSubmit = { async() => await getCertificate(id) .then(resp => resp.json()) .then(data => console.log(data)) }> Whenever there is an erro ...

The NUXT project encounters issues when trying to compile

I am currently working on an admin panel using the nuxt + nest stack. I am utilizing a template provided at this link: https://github.com/stephsalou/nuxt-nest-template While in development mode, the project starts up without any issues. However, when I ...

AngularJS directive for automatically resizing Dygraph on page load

Could someone please assist me with resizing my graph inside tabs using Angular? When I initially load the graphs, they don't display unless I manually resize the window. How can I ensure that the graphs are loaded and fill the div on the first load? ...

Having difficulty retrieving data despite providing the correct URL

I am encountering an issue with a fetch function designed to retrieve a JSON web token. Despite verifying the correctness of the URL, the function is not functioning as expected. Below is the front-end function: const handleSubmit = async (e) => { ...

Obtain the name of the model in Vue.js using either the input's ID or name attribute

Is it possible to retrieve the model name using the input ID? <input v-model="data.name" id="name_db"> I have a value for data.name in the database. Prior to using Vue.js, I accomplished this task with the following code: values ...

combine and refresh identical items within an array

Currently, I am in the process of creating a prototype for an item-list and a shopping-cart. Both components function as standalone entities but are connected through a vuex-store. The item-list contains various elements that can be added to the shopping-c ...

Testing Vue Components: A Comprehensive Guide

Currently, I have a simple counter component in Vue. <div> + </div> <input type="text" v-model="countData" /> <div> - </div> If you want to see the detailed code for this component, click here - https://github.com/Shreer ...

The information is undefined, yet it is being recorded in the console

After retrieving data from the backend, it seems to be undefined when I try to use it. However, I can see the data logged in the console when using console.log. //I attempted to fetch data using axios but encountered a 404 error and received und ...

The appearance of SVG markers varies depending on the screen they are viewed on

Latest Update: I have finally figured out the screen issue. The device pixel ratio is to blame. Icons appear smaller on devices with lower window.devicePixelRatio. One solution I found is to adjust the icon size based on window.devicePixelRatio, like this ...

What takes precedence in npm scripts - local dependencies or global ones?

When using npm scripts, the ./node_modules/.bin path is automatically added to your PATH. This means that by simply running npm test with the provided package.json, npm will utilize the local version of mocha located in ./node_modules/.bin. "scripts": { ...

Utilizing JQuery to merge variable identifiers

Imagine a scenario where the variables are structured this way: localStorage.var1a = 0; localStorage.varnum = 1000; Now, consider the following code snippet: for(x = 1; x < localStorage.varnum; x++){ if(localStorage.var.x.a > 0){ localStora ...

Looking for guidance on JavaScript - Implementing a different font family for each div element

I need help with customizing the font family for each individual post on my website. Currently, I am able to assign a cursive font to all posts within a class, but I would like each post to have its own unique font. Since I am doing this on load, I am fa ...

The two-word string is failing to pass through the query string

I've been working on passing multiple values through the query string. So far, I have successfully passed single-word values to a PHP page using jQuery. However, I encountered an issue when trying to pass a user's name like "Vishal Deb" as it onl ...

What is the basic structure of a JSON-like object?

How can data be effectively stored in a JSON-like structure? I have noticed two different approaches to storing data within a json object, each with its own method for accessing the data (illustrated using examples in Python): Approach 1: obj1 = [ {" ...

What is the best way to programmatically select a checkbox that was created dynamically using jQuery?

I've been scouring the internet trying to find information on what I'm attempting to accomplish, but so far I haven't come across anything helpful. The issue I'm facing is with a form that has a section dynamically added using JavaScri ...

What steps should be taken to resolve the error message "EROFS: read-only file system, attempting to open '/var/task/db.json'?"

const jsonServer = require('json-server') const cors = require('cors') const path = require('path') const server = jsonServer.create() const router = jsonServer.router(path.join(__dirname, 'db.json')) const middlewa ...

JavaScript error leading to ERR_ABORTED message showing up in the console

When I try to load my HTML page, my JavaScript code keeps throwing an error in the console. I am attempting to import some JavaScript code into VSCode using an app module for future reuse. The code is being run through a local server. Error Message: GET ...

Loading page with asynchronous JavaScript requests

As I send my AJAX request just before the page loads and then call it on the same page afterwards, here is what it looks like: <input type="text" class="hidden" id="storeID" value="<?php echo $_GET['store']; ?>"> $(document).ready(fu ...

Extract a selection from a dropdown menu in ReactJS

I have multiple cards displayed on my screen, each showing either "Popular", "Latest", or "Old". These values are retrieved from the backend. I have successfully implemented a filter option to sort these cards based on popularity, age, etc. However, I am u ...

When flex items are stacked in a column, the bottom portion may be truncated

(Edit) Check out the codepen example here. I am working on creating a stack of cards using Vue.js and flexbox to showcase different apps on my website. Each card is represented by a component and I utilize Vue's `for` function to display cards with t ...