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()。
我的問題是,是否有可能將數據從第一個函數轉換爲使用該變量的第二個函數。 我找不到任何簡單的東西來幫助我解決這個問題。