I am using vue js and axios.
Here is what I am trying to do:
My "outlines" array gets usually between 3 to 9 entries. I would like to run an axios request(runSecondFunction()) on each entry, but only run 1 request at a time(wait for each record to be fetched before initiating another next request, and not all at once. If one of the requests fails, have an error message. Right now as it is, it works but some of the request finish before the others and my index position is wrong 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 => {
//
});
}
Any idea how to do this please?
Thanks
CodePudding user response:
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 => {
CodePudding user response:
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.