4

I'm having trouble with the following code snippet. I can't access userId from within the callback function, and I can't return whether whitelistedUserIds contains the userId or not. According to the debugger, when I step inside the callback, userId is undefined.

Could anyone explain why? and how to fix this? I've been off javascript for quite a while...

function userInWhitelist(userFileName) {
  var userId = userFileName.replace('.txt', '');
  request({
    url: whitelistURL
  }, function(err, resp, body, userId) {
    if (resp.statusCode == 200) {
      var users = JSON.parse(body).data;
      var whitelistedUserIds = _.map(users, (user) => { return user.id; });
      // How to access userId ??
      // How to return whitelistedUserIds.includes(userId)
    }
  });
1
  • 1
    It's called shadowing. Give one or the other a different name. Commented Feb 23, 2016 at 17:06

1 Answer 1

4

The callback's userId is shadowing the outer one. Just remove userId from callback

function userInWhitelist(userFileName) {
  var userId = userFileName.replace('.txt', '');
  request({
    url: whitelistURL
  }, function(err, resp, body) {
    if (resp.statusCode == 200) {
      var users = JSON.parse(body).data;
      var whitelistedUserIds = _.map(users, (user) => { return user.id; });
     // here you have access to userId
    }
  });
Sign up to request clarification or add additional context in comments.

2 Comments

You might want to mention that the callback's userId is shadowing the outer one. Just saying remove doesn't tell anyone what really happened.
@JosephtheDreamer My english very bad, for me to explain is harder than just show right code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.