Javascript 访问另一函数中全局定义变量的函数中的数据集
我在JS还是有点不在行,因此我有以下问题。我有这个JS:Javascript 访问另一函数中全局定义变量的函数中的数据集,javascript,node.js,Javascript,Node.js,我在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 { lo
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()
我的问题是,是否可以使用变量将数据从第一个函数传递到第二个函数。
我找不到任何足够简单的方法来帮助我解决这个问题。问题是,在调用其他函数之前,您的
client.logOn
参数已初始化。将该调用放在另一个函数中,并在另一个函数之后调用它
function myLogOn() {
client.logOn({
accountName: config.username,
password: config.password,
twoFactorCode: twoFactorAuthCode
});
};
myLogOn();
如果
fs.readFile
是异步的,您甚至可能需要将对logOn
的调用移动到回调函数中。问题是,在调用其他函数之前,您对client.logOn
的参数已初始化。将该调用放在另一个函数中,并在另一个函数之后调用它
function myLogOn() {
client.logOn({
accountName: config.username,
password: config.password,
twoFactorCode: twoFactorAuthCode
});
};
myLogOn();
如果fs.readFile
是异步的,您甚至可能需要将调用移动到logOn
以进入回调函数