How to make the loop variable in calbeck asynchronou request?

How to use the variable key in kaleke, if at the time of the launch of the first processor, key=last key.
Tried to save in a temporary variable inside the loop - did not help.
Alternatively, pass the key as the argument to the function, but how to do it in the npm module request?
for(var key in reqObj) {
 request(options, (err, res, body) => {
 if (!err && res.statusCode == 200) {
 resultObj[key] = body;
}
....
});
}
July 9th 19 at 13:33
3 answers
July 9th 19 at 13:35
Solution
for(var key in reqObj) {
(function(key){
 request(options, (err, res, body) => {
 if (!err && res.statusCode == 200) {
 resultObj[key] = body;
}
....
});
})(key)
}
July 9th 19 at 13:37
Solution
The easiest way to replace the var in a let or const.

'use strict';

let o = { a: 1, b: 2, c: 3 };

for (var k in o) {
 process.nextTick(() => console.log(k, o[k]));
}

for (const k in o) {
 process.nextTick(() => console.log(k, o[k]));
}


$ node a.js
c 3
c 3
c 3
a 1
b 2
c 3
July 9th 19 at 13:39
Using promise

for(var key in reqObj) {
 new Promise(function(resolve, reject) {
 var k = key;
 request(options, (err, res, body) => {
 if (!err && res.statusCode == 200) {
 resultObj[k] = body;
}
....
});
});
}
Promises nothing to do with it, it's in the circuit. - aniya commented on July 9th 19 at 13:42

Find more questions by tags Node.jsJavaScriptWeb Development