Reputation: 193
Good day. Here is a function I have:
function LoginClient(user) {
return new Promise((resolve, reject) => {
SteamClients[user.username].client.logOn({
accountName: SteamClients[user.username].details.username,
password: SteamClients[user.username].details.password,
twoFactorCode: SteamTotp.generateAuthCode(SteamClients[user.username].details.shared_secret)
})
SteamClients[user.username].client.on('loggedOn', ()=> {
Debug.emit('message', `Client logged in: ${SteamClients[user.username]}`);
})
SteamClients[user.username].client.on('webSession', (sid, cookies)=> {
manager.setCookies(cookies);
community.setCookies(cookies);
Debug.emit('message', `Client logged into websession: ${SteamClients[user.username]}`);
})
})
}
What I want to achieve with this function is that when the client is logged on and so is the websession, only then is the promise resolved. The reason why is because timing is important.
Upvotes: 2
Views: 38
Reputation: 23495
Not an answer, just syntax. You could use of destructuring to make your code lighter and easier to read.
function LoginClient(user) {
return new Promise((resolve, reject) => {
const {
client,
details: {
username,
password,
shared_secret,
},
} = SteamClients[user.username];
client.logOn({
accountName: username,
twoFactorCode: SteamTotp.generateAuthCode(shared_secret),
password,
});
let isLoggedOn = false;
let hasWebSession = false;
client.on('loggedOn', () => {
Debug.emit(
'message',
`Client logged in: ${SteamClients[user.username]}`,
);
isLoggedOn = true;
if (hasWebSession) {
resolve();
}
});
client.on('webSession', (sid, cookies) => {
manager.setCookies(cookies);
community.setCookies(cookies);
Debug.emit(
'message',
`Client logged into websession: ${SteamClients[user.username]}`,
);
hasWebSession = true;
if (isLoggedOn) {
resolve();
}
});
});
}
Upvotes: 1
Reputation: 136074
A quick solution would be to maintain 2 booleans for each event ocuring and only calling resolve
if both are true (or, more accurately when the other is true from an event handler)
function LoginClient(user) {
return new Promise((resolve, reject) => {
SteamClients[user.username].client.logOn({
accountName: SteamClients[user.username].details.username,
password: SteamClients[user.username].details.password,
twoFactorCode: SteamTotp.generateAuthCode(SteamClients[user.username].details.shared_secret)
})
var isLoggedOn = false;
var hasWebSession = false;
SteamClients[user.username].client.on('loggedOn', ()=> {
Debug.emit('message', `Client logged in: ${SteamClients[user.username]}`);
isLoggedOn = true;
if(hasWebSession) resolve();
})
SteamClients[user.username].client.on('webSession', (sid, cookies)=> {
manager.setCookies(cookies);
community.setCookies(cookies);
Debug.emit('message', `Client logged into websession: ${SteamClients[user.username]}`);
hasWebSession = true;
if(isLoggedOn) resolve();
})
})
}
Upvotes: 3