I haven't really worked much with asynchronous code so I'm wondering if I am doing something wrong/something could go wrong. Right now of all the test cases that I have done, my code has worked but I'm not sure if I will get side effects or not.
I won't post any of the business logic, just the iteration part with the asynchronous function in it:
function asyncInIteration(skinArray) {
request("/someaddresshere", function (err, response, data) {
var left = something.length;
for (var i = 0;i<something.length;i++) (function (i) {
request("/someotheraddress", function (err, response, data) {
if (--left === 0) {
console.log("End of for loop");
}
})
})(i);
});
}
Basically, what I am trying to do with this code is loop through an array (skinArray
) and add values to it via sending HTTP requests.
The most important thing for me is that:
- Every value of
i
should only be repeated once. - When I call
--left === 0
, that has to be called once, and only after all values ofi
have been gone through.
If someone wants to see the code with the business logic, you can find it here.
request()
operation finishes. Do you need therequest()
results in order when you're done? Are you OK with all therequest()
operations being launch in parallel (all in-flight at the same time)? \$\endgroup\$for
loop runs and initiates all the requests. At that point, thefor
loop is done and any code that comes after it executes. Then, some time later the firstrequest()
finishes and calls its callback. Then, sometime later, the next does. Then, finally the last one completes and yourleft
variable will hit0
. Thefor
loop was done long before this. \$\endgroup\$