I have a view-request which returns amount X and will then fire a function X times through a for-loop. It works everything but due to the asynchronous request, I do not get the correct i-value that the function/request was fired with. The (javascript) code:
X = [0,2,4,6]
for(var i = 0; i < X.length; i++) {
// i is the user ID
contract.getUser(i, function (err, result) {
if (err) {
/////
}
else if (result) {
// I want to return the current i-value (loop-value),
// But due to the asynchronous request, it always returns the
// last value (in our example 4)
console.log(i);
}
}
}
Everything works fine (I get the user) but I can't redirect to for example url.com/user/ID because the ID (i) is always the same.
Thanks for help!
iin the call togetUseris fine because it happens synchronously (so it receives the current value ofifor that iteration of the loop). It's just the callback that's problematic because it sees the current value ofiat that time, which is after the loop has finished. – user19510 Apr 22 '19 at 18:31