Wednesday, 24 May 2017

Using async/await with done()/next() middleware functions

I'm starting to use async/await. Generally, what is a pattern to use await with middleware done/next functions?

Specifically, 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));
}



via Michael Cole

No comments:

Post a Comment