D
D
Dark_Scorpion2016-05-17 18:50:42
JavaScript
Dark_Scorpion, 2016-05-17 18:50:42

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

2 answer(s)
D
Deodatuss, 2016-05-17
@Dark_Scorpion

for(var key in reqObj) {
(function(key){
  request(options, (err, res, body) => {
    if (!err && res.statusCode == 200) {
       resultObj[key] = body;
    }
    ....
  });
})(key)
}

N
Nicholas, 2016-05-17
@ACCNCC

Through a 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;
            }
        ....
        });
    });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question