Issue arising due to incorrect array index placement following the axios request

I am currently utilizing vue js and axios for my project.

Here is the challenge I am facing:

Typically, my "outlines" array contains anywhere from 3 to 9 entries. I want to send an axios request (runSecondFunction()) for each entry, but execute only one request at a time (waiting for each record to be fetched before starting the next request, instead of all at once). In case any of the requests fail, display an error message. While the current setup works, some requests finish before others leading to incorrect index positions in the response.

method1(){
       for (const [index, value] of this.splitOutlines.entries()) {
          this.runSecondFunction(value, index);
             }
             }

    runSecondFunction(value, index){
           let formData = {
                    title: this.blog.value,
                    subheading: value
                };
                axios.post('/dashboard/paragraphs', formData).then((response) => {
                    this.articles.push({
                        index: index,
                        subheading: response.data.subheading,
                        paragraph: response.data.data.ideas[0],
                    });
                }).catch(error => {
                     //
                });
    }
    

If you have any insights on how to achieve this, I would greatly appreciate it.

Thank you

Answer №1

If you are insistent on preventing these processes from running concurrently, there are a couple of options available to you. One approach is to have method1 call an async function and wrap it in a try-catch block while creating a new array to store the results before returning or assigning it elsewhere. For example:

method1(){
   (async function () {
     const requests = []
     for (const [index, value] of this.splitOutlines.entries()) {
       try {
         const res = await this.runSecondFunction(value, index);
         requests.push(res)
       } catch (e) {
         requests.push(e)
       }
     }
    return requests
    )().then(reqs => {
       // perform additional actions with the completed requests.
    })

}

This approach ensures that the order of requests is preserved and only one request is processed at a time.

Alternatively, you may need to implement a recursive solution within the .then method.

EDIT::

I neglected to mention that in your runSecondFunction method, you must return the promise, as shown below:

runSecondFunction(value, index){
    let formData = {
        title: this.blog.value,
        subheading: value
    };
    return axios.post('/dashboard/paragraphs', formData)

}

In this way, the await statement in mehtod1 will assign the result to the variable

res</code (which can be manipulated as needed).</p>
<p>However, avoid handling errors within <code>runSecondFunction
if you want them to be included in the result array.

Answer №2

Instead of pushing an error object into the array, another option is to directly assign it to a property of the articles object.

axios.post('/dashboard/paragraphs', formData).then((response) => {
    this.articles.push({
        index: index,
        subheading: response.data.subheading,
        paragraph: response.data.data.ideas[0],
    });
}).catch(error => {
    this.articles.push({ error });
});

Alternatively, you could transform the articles array into a plain object and assign values to properties within that object instead of using push method.

axios.post('/dashboard/paragraphs', formData).then((response) => {
    this.articles[index] = {
        index: index,
        subheading: response.data.subheading,
        paragraph: response.data.data.ideas[0],
    }
}).catch(error => {

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

Issue with image magnification on Internet Explorer 9 using the Cloud Zoom plugin extension for Joomla

Recently, I've been utilizing a Joomla plugin called cloud zoom to enhance our gallery by providing an image magnification effect when hovering over the large image. You can see it in action on this link here. While it works flawlessly on most browser ...

Can the execution of one endpoint in a Node.js Express API prevent access to another endpoint?

Hello there, I am currently diving into the world of Nodejs and Express and could use some guidance. Currently, I have set up two endpoints: /addcar and /viewcar Upon sending a post call to /addcar, I have created an infinite loop to continuously run. Ho ...

What is the best way to display an image in Vuetify when the URL is found within my filtered array?

I need to display various images depending on the card being loaded. <tr v-for="location in filteredLocation" v-bind:key="location"> <v-card class="mx-auto"> <v-img class="white--text align-end" height="200px" ...

Issues with Angularjs in production when used with Rails

I am currently facing an issue while attempting to deploy a Rails application with Angularjs on Bluemix. AngularJS is being used for the front end MVC. Despite the application running smoothly on my local machine, when deployed on Bluemix, Angularjs fails ...

When located at the bottom of a page, the Div element fails to display

I need some help with my javascript code. I am working on creating a scrollable panel that closes when scrolled and reveals a #toTop div when the bottom of the page is reached. Below is the function code I have written, but for some reason, the #toTop div ...

Employing the findOne method repeatedly in a loop can significantly slow down operations in Node.js

Currently, I am working on a project using Node.js in conjunction with MongoDB, specifically utilizing Monk for database access. The code snippet I have is as follows: console.time("start"); collection.findOne({name: "jason"}, function(err, document) { ...

Angular directive and the concept of isolating scopes

I am facing an issue with a directive that dynamically adds divs to the template. Every time I add a new one, the previously created ones are replaced by the new content. I have tried isolating the directive's scope using scope: {} and scope: true, bu ...

Is it possible to halt component rendering with Composition in VueJS?

In my component, I have been using a computed property along with a v-if statement to prevent it from rendering if certain basic props were not provided. For example: <template> <div v-if="basicPropsProvided"> Blabla </di ...

Executing an Ajax call to trigger a NodeJS function that executes a bash script

I have created a bash script to generate a JSON file that needs to be parsed and sent to the client-side JavaScript for display. My goal is to achieve this without refreshing the page and without using jQuery. I attempted to use Axios but seem to be facing ...

Incorporating an external Angular.js library into a Vue.js Single File Component

I am working with a Single File Component in Vue.js that includes the following code. The plasmid tag should be rendered by the angularplasmid.complete.min.js file, but it doesn't seem to be working. I'm wondering if this is the correct way to i ...

Vue inexplicably fails to remove correct component from the list

Even though I have included :key="index", it is still not functioning as required. For instance, if you add 6 items and select something from the third item and click on the remove button for that item, it deletes a different item instead of the one select ...

Understanding the fundamentals of event handling in JavaScript

Is there a way to access the object that called the event handler within the event handler function itself? For example: marker.on('dragend', onDragEnd); In this case, marker is the object that triggers the ondragEnd function on the Dragend eve ...

Utilizing factory service within a decorator in AngularJS

Utilizing the TextAngular plugin and attempting to customize a toolbar, I am striving to inject my own service (LinkService) into the module but encountering an [$injector:unpr] Unknown provider issue. module.config(function($provide, LinkService){ $p ...

Transitioning between modals using Tabler/Bootstrap components in a ReactJS environment

Currently, I am constructing a Tabler dashboard and incorporating some ReactJS components into it. Initially, I used traditional HTML pages along with Jinja2 templates. However, I have now started integrating ReactJS for certain components. I prefer not t ...

Experiencing issues and alerts when handling JSON data

Here is the Json data I am attempting to represent using Json-LD : var schemaOrg = angular.toJson({ "@context": "http://schema.org", "@type": "RealEstateAgent", "RealEstateAgent": { ...

Displaying a div and ensuring it remains visible upon clicking

$(document).ready(function() { $('#input').focusin(function() { if ($(this).val() != '') { $('#div').show(); } else { $('#div').hide(); } $('#input').keyup(function() { / ...

Identify distinct prefixes and eliminate them from an array of strings

If you have an array of strings in Javascript, is there a way to identify the common prefix among all the strings and then remove that prefix from each string? For instance: ["05098701", "05012302", "0545621", "0509301"] The common prefix in this case w ...

Illustrative demonstration of Vue with TypeScript

I am currently working on developing a HelloWorld application using Vue.js and TypeScript. index.html <script data-main="app.js" src="node_modules/requirejs/require.js"></script> <div id="app">{{text}}</div> app.ts import Vue f ...

Chat box custom scrollbar always positioned at the bottom

I have a personalized chat box where I included overflow-y for scrolling functionality. However, every time I input a message in the text box, it displays at the top of the scrollbar window. Is there a way to automatically show the most recent message I ...

An error will occur if you try to modify the state of a component from outside the component

Creating a modal component that triggers a bootstrap modal from any section of the application and then defines custom states for that component externally. It is functional, however, an error message consistently appears upon opening the modal, and I am u ...