Answer the question
In order to leave comments, you need to log in
How to add a loop variable to the callback of an asynchronous request?
How to use the key variable in the callback if by the time the first handler is run, key=last key.
I tried to save to a temporary variable inside the loop - it did not help.
It's an option to pass key as a function argument, but how do you do that in the npm request module?
for(var key in reqObj) {
request(options, (err, res, body) => {
if (!err && res.statusCode == 200) {
resultObj[key] = body;
}
....
});
}
Answer the question
In order to leave comments, you need to log in
for(var key in reqObj) {
(function(key){
request(options, (err, res, body) => {
if (!err && res.statusCode == 200) {
resultObj[key] = body;
}
....
});
})(key)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question