我仍然是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 :(得分:0)
问题是,在调用其他函数之前,client.logOn
的参数是初始化。将该调用放在另一个函数中,然后在另一个函数之后调用它。
function myLogOn() {
client.logOn({
accountName: config.username,
password: config.password,
twoFactorCode: twoFactorAuthCode
});
};
myLogOn();
如果fs.readFile
是异步的,您甚至可能需要将调用移至logOn
以进入回调函数。