Passport JS and custom async/await function

Viewed 427

I'm using Passport JS local strategy and would like to add a custom function that does some verification on the email provided by the user

async function checkEmail(email) {
  const url = `https://endpoint-to-url/${email}`;
  await fetch(url)
    .then(response => response.json())
    .then(async json => {
      let result;
      if (json.status === 200 && json.temporary === true) {
        result = true;
      } else {
        result = false;
      }
      return result;
    })
    .catch(async function(error) {
      console.log(`Error whilst checking email ${error}`);
    });
}

Passport JS

passport.use(
'local-signup',
new LocalStrategy(
  {
    usernameField: 'signup_email',
    passwordField: 'signup_password',
    passReqToCallback: true,
  },
  async (req, email, password, done) => {
    process.nextTick(async () => {
      const isTempEmail = await checkEmail(req.body.signup_email);
      if (isTempEmail === true) {
        return done(null, false, { errors: 'Unable to use this email' });
      }
    });
   }
  )
);

Each time isTempEmail returns undefined, though if I log out what is returned at the end of checkEmail(email) is either true or false.

I feel like I'm mixing callbacks and async/await functionality and would like to know where I am going wrong.

1 Answers

Currently your checkEmail function doesn't return anything. Instead:

return fetch(url)
    .then(response => response.json())
    .then(async json => {
      let result;
      if (json.status === 200 && json.temporary === true) {
        result = true;
      } else {
        result = false;
      }
      return result;
    })
    .catch(async function(error) {
      console.log(`Error whilst checking email ${error}`);
    });

This is because you want to return the result of the response to the caller. You don't need to return await since that's redundant—async functions will always return a promise. If the return value is not a promise (e.g. you return await fetch(url)), it is wrapped in a promise. before returning to the caller. So return fetch(url) is sufficient.

You can even simplify this further by converting your .then calls into awaits and write it as if it were synchronous.

Related