Reputation: 16247
I'm starting to use async/await. Generally, what is a pattern to use await with middleware done/next functions?
For example, how could I replace .then() in the code below with await? localAuthenticate
is done/next middleware. Do I need to make a separate async
function to use await
inside it?
I'd like something like this (even better w/o the try/catch):
function localAuthenticate(User, email, password, hostname, done) {
try { // where is async?
// Find user
let user = await User.findOne({ email: email.toLowerCase() }).exec()
if(!user) return done(null, false, { message: 'This email is not registered.' });
// Test password
user.authenticate(password, function(authError, authenticated) {
if(authError) return done(authError);
if(!authenticated) return done(null, false, { message: 'This password is not correct.' });
return done(null, user);
});
} catch(err) { done(err); }
}
Original code from Passport.js authentication middleware:
function localAuthenticate(User, email, password, hostname, done) {
User.findOne({
email: email.toLowerCase()
}).exec()
.then(user => {
if(!user) {
return done(null, false, {
message: 'This email is not registered.'
});
}
user.authenticate(password, function(authError, authenticated) {
if(authError) {
return done(authError);
}
if(!authenticated) {
return done(null, false, { message: 'This password is not correct.' });
} else {
return done(null, user);
}
});
})
.catch(err => done(err));
}
Upvotes: 3
Views: 2479
Reputation: 24290
await
can only be called within an async
function - see the MDN documentation
async function localAuthenticate(User, email, password, hostname, done)
.try/catch
is the way to catch exceptions when using await
, instead of the .then/.catch
you are used to when dealing with Promises directly.Your function would approximate, when using async/await
:
async function localAuthenticate(User, email, password, hostname, done) {
try {
// Find user
let user = await User.findOne({ email: email.toLowerCase() }).exec()
if (!user) {
return done(null, false, { message: 'This email is not registered.' })
}
user.authenticate(password, function (authError, authenticated) {
if (authError) {
return done(authError)
}
if (!authenticated) {
return done(null, false, { message: 'This password is not correct.' });
}
return done(null, user);
})
} catch (err) {
done(err)
}
}
Further reading:
Upvotes: 2