If it is a JavaScript program written using Node.js that will look through all employees, fetch some data, do some calculation, and post it back to another server:
// without error handling to keep it simple for now
for (let employee of employees) {
new Promise(function(resolve) {
fetch(someUrlToServerA + employee.id).then(resolve);
}.then((data) => {
let result = doCalculations(data);
return postData(someUrlToServerB + employee.id, result).then(resolve);
}.then(() => console.log("Finished for", employee.id));
}
console.log("All done.");
If written using async/await, it maybe roughly equivalent to:
(async function(){
for (let employee of employees) {
data = await fetch(someUrlToServerA + employee.id);
let result = doCalculations(data);
await postData(someUrlToServerB + employee.id, result);
console.log("Finished for", employee.id);
}
console.log("All done.");
})();
Let's say if there are 6000 employees, then won't the program (running using Node.js) keep on making requests to ServerA, and in fact print out "All done"
almost instantly (maybe within seconds), but now just have 6000 threads all trying to get data from ServerA, and then do calculations, and post to ServerB? Would there be a better way to do it?
It seems there might be some benefits to making requests in parallel:
if each request to ServerA takes 3 seconds, then making parallel requests to it probably will save some time if it can return 4 requests within the 3 seconds. But if ServerA is sent to many requests at the same time, then it may just bottle up the requests and just be able to process a few requests at a time. Or, using this method, does the system actually limit the amount of simultaneous fetches by limiting the number of connections at the same time. So let's say if it limits 4 connections at the same time, then "All done"
is printed quickly, but internally it is processing 4 employees at the same time, so it is alright? If ServerA and ServerB don't complain about having several requests at the same time, and the calculation, let's say take milliseconds to finish, then this method may take 1/4 of the time to finish compared to the synchronous version?