I have a bunch of functions that return promises and need to chain them together. However, it's currently difficult to read and I would expect it to be even harder to maintain.
I have a function that performs the following actions:
- Logs off any inactive users.
- Verifies a user's credentials.
- Creates a session and logs the user in.
Is there a better way?
generateToken: function (email, password) {
return new Promise((resolve, reject) => {
//Kill inactive sessions first
module.exports.destroyInactive()
.then(() => {
//Verify that the password matches the user
users.checkPassword(email, password, sharedSecret)
.then((user) => {
//Check if there is another user already signed in, if there is then we can't
//produce another token until they are signed out.
signedon.getByEmailAddressThisProcess(email)
.then((result) => {
let rows = result[0];
if (rows.length > 0)
return reject('A user with email: ' + email + ' is already logged in.');
//Get the current XPROCESS.
xprocess.getByProcessId(process.pid)
.then((xproc) => {
//Create a brand new session object
let session = generateSession(user);
//Save the session in the signed on table.
signedon.signin(session, xproc.pid)
.then(() => {
resolve(parseSessionToToken(session));
},
reject);
},
reject);
},
reject);
},
reject);
},
reject);
});
},