简体   繁体   中英

How to access outer variables from a callback function?

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)
    }
  });

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
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM