I have a object of 365 elements like this:
data = [ { "a": "a", "b": "b", "c": "c", "date": 1663192800000},
{ "a": "a", "b": "b", "c": "c", "date": 1663293800000}
{ "a": "a", "b": "b", "c": "c", "date": 1643294800000}
...
]
I have tried something like this, but the process is slow:
for(var i = 0; i<this.data.length; i ){
Promise.all([axios.post( "URL",this.data[i])]).then((response) => this.getData())
}
How can I speed up the sending of data to the db?
CodePudding user response:
I think it would be better to update the backend code with batch insert and send all entries as one request, if possible.
But if this is the only way, First, your code is not efficient because you use Promise.all
on each element. it would be better to use map
with the data
inside the Promise.all
to resolve altogether.
Promise.all(this.data.map(i => axios.post("URL",i)).then((response) => this.getData())
CodePudding user response:
The approach is wrong. You are performing a single request with Promise.all for each array member this way.
Promise.all
should receive the "already mapped" data as a axios post.
// Maps the data array into an array of functions that will return a axios call
const myPromiseList = this.data.map((thing) =>
() => axios.post("URL", thing));
Promise.all(myPromiseList)