[Vuejs]-Problem with array index after axios call

2👍

If you’re really adamant about these not running concurrently, then you’ll have to do one of two things. You can make method1 call an async function and throw a try catch around it while composing an new array and returning or setting that somewhere else. e.g.

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 => {
       // do other stuff with the completed requests.
    })

}

This should guarantee the order of the requests is respected and only one will be run at a time.

Otherwise, you’ll have to do a sort of recursive implementation in the .then method.

EDIT::

I forgot to mention that in your runSecondFunction method, you need to return the promise, so it should look like this:

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

}

This way, the await from mehtod1 will assign the article to what I called res (You can of course manipulate this data any way you need).

But don’t handle the error within runSecondFunction if you want them to be present in the array.

1👍

One approach would be to push an error object into the array if there’s an error.

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 });
});

Or you could change the articles to be a plain object instead of an array, and assign to properties of the object instead of pushing.

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

Leave a comment