At this moment I have a webpage in which a long list of Axios POST calls are being made. Now, the requests seem to be sent in parallel (JavaScript continues sending the next request before the result is received).
However, the results seem to be returned one by one, not simultaneously. Let's say one POST call to the PHP script takes 4 seconds and I need to make 10 calls. It would currently take 4 seconds per call, which would be 40 seconds in total. I hope to find a solution to both and receive all results at approximately the same time (~4 seconds) instead of ~40 seconds.
Now I've read about threads, multithreading in NodeJS using Workers. I've read that JavaScript itself is only single-threaded, so it may not allow this by itself.
But I'm not sure where to go from here. All I have are some ideas. I'm not sure whether or not I'm heading into the right direction and if I am, I am not sure how to use Workers in NodeJS and apply it in my code. Which road should I take? Any guidance would be highly appreciated!
Here is a small piece of example code:
for( var i = 0; i < 10; i++ )
{
window.axios.post(`/my-url`, {
myVar: 'myValue'
})
.then((response) => {
// Takes 4 seconds, 4 more seconds, 4 more seconds, etc
// Ideally: Takes 4 seconds, returns in the same ~4 seconds, returns in the same ~4 seconds, etc
console.log( 'Succeeded!' );
})
.catch((error) => {
console.log( 'Error' );
});
// Takes < 1 second, < 1 more second, < 1 more second, etc
console.log( 'Request sent!' );
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…