简体   繁体   中英

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?

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

await can only be called within an async function - see the MDN documentation

  • Your function needs to be async function localAuthenticate(User, email, password, hostname, done) .
  • The 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM