2016-06-07 101 views
1

我在JS上仍然是一个小菜鸟,因此我有以下问题。我有这个JS:在另一个函数中访问一个全局变量定义函数中的数据集

var twoFactorAuthCode; 

fs.readFile('file.2fa', function (err, data) { 
    if (err) { 
     logger.warn('Error reading neyotbot1.2fa. If this is the first run, this is expected behavior: '+err); 
    } else { 
     logger.debug("Found two factor authentication file. Attempting to parse data."); 
     twoFactorAuth = JSON.parse(data); 
     SteamTotp.getTimeOffset(function (error, offset, latency) { 
      if (error) { 
      logger.warn('Error retrieving the time offset from Steam servers: ' + error); 
      } else { 
      timeOffset = offset + latency; 
      } 
     }); 
     console.log(twoFactorAuthCode); //returns undefined 
     twoFactorAuthCode = SteamTotp.getAuthCode(twoFactorAuth.shared_secret, timeOffset); 
     console.log(twoFactorAuthCode); //returns what is expected 
    } 
    console.log(twoFactorAuthCode); //also returns what is expected 
}); 

client.logOn({ 
    accountName: config.username, 
    password:  config.password, 
    twoFactorCode: twoFactorAuthCode //this is still set as undefined 
}); 

我的问题是,虽然可变twoFactorAuthCode有一个全球范围内,当它在fs.readFile()函数赋值,它不会到下一个功能携带数据client.logOn()。

我的问题是,是否有可能将数据从第一个函数转换为使用该变量的第二个函数。 我找不到任何简单的东西来帮助我解决这个问题。

回答

0

问题是你的参数client.logOn在调用其他函数之前初始化了。将该调用放入另一个函数中,并在另一个函数之后调用它。

function myLogOn() { 
    client.logOn({ 
    accountName: config.username, 
    password:  config.password, 
    twoFactorCode: twoFactorAuthCode 
    }); 
}; 
myLogOn(); 

如果fs.readFile是异步的,你甚至可能需要将呼叫转移到logOn是回调函数内。

相关问题