Si-N
Si-N

Reputation: 1495

Capture value from loop in callback

I have a loop which performs an async get method which calls a callback when completed. In the callback, I need to know which loop the callback was linked to.

I'm guessing this might be to do with closures, but don't really understand what I need to change to capture the key from the for loop.

Side note: I'm aware looping through Redis keys is generally bad practice, but there are only a handful of keys in this case.

 let redisGetCallback = function(err, getResponse) {
  numberOfLoops++;
  let user = JSON.parse(getResponse);

  if(user.uid === userInfo.uid) {
    user.grantedPermission = true;
    let userSerialised = JSON.stringify(user);

    redis.set('!!NeedTheKeyFromTheForLoopBelowHere!!', userSerialised.....

  } else if (numberOfLoops === numberOfKeys) {
    cb(false);
  }
};

for (let i = 0; i < keys.length; i++) {
  redis.get(keys[i], redisGetCallback);
}

Upvotes: 0

Views: 203

Answers (1)

rsp
rsp

Reputation: 111394

If you want to know the value of i in the given callback then instead of:

for (let i = 0; i < keys.length; i++) {
  redis.get(keys[i], redisGetCallback);
}

run it with:

for (let i = 0; i < keys.length; i++) {
  redis.get(keys[i], redisGetCallback(i));
}

and change your redisGetCallback from:

let redisGetCallback = function(err, getResponse) {
};

to:

let redisGetCallback = number => (err, getResponse) => {
};

and you'll have the correct number available as number inside of your callback.

Of course the may be other problems with your implementation so you may need to make more changes, but the basic ideas is that instead of relying on the global variables it's better to pass the correct values as parameters.

Remember that you never know the order in which the callbacks will be called so your last callback may be called first and if you count the number of the callback in the order it is run it doesn't necessarily be the same as the number of the callback in the order it was registered.

Upvotes: 1

Related Questions