簡體   English   中英

如何從回調函數訪問外部變量?

[英]How to access outer variables from a callback function?

我在使用以下代碼片段時遇到問題。 我無法從回調函數中訪問userId ,並且我無法返回whitelistedUserIds是否包含userId 根據調試器,當我進入回調時, userId是未定義的。

誰有人解釋為什么? 以及如何解決這個問題? 我已經離開javascript很長一段時間了...

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

回調的userId正在遮蔽外部的。 只需從回調中刪除userId

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM