Home > Enterprise >  Should I use this async/await and .exec with mongoose and google-auth-library?
Should I use this async/await and .exec with mongoose and google-auth-library?

Time:04-06

I have this backend (nodeJS) where I receive an IdToken in an async function

route in app.js

app.post("/login", login.login );

login.js

exports.login = async (req, res) => { 
  const token = req.body.token;
  const client = new OAuth2Client(googleID, googleSecret); 
  const ticket = client.verifyIdToken({
      idToken: token,
      audience: googleID
  });  
 await ticket.then(data => {
    User.findOne().and([{
      "email": data.payload.email
    }])
    .exec((err, user) => { //code}

But I read somewhere that isn't recommendable to mix async, .then and .exec Is there a problem with my code or a suggestion to improve it? can this cause bottleneck?

CodePudding user response:

It's all about personal preference, both does the same thing. Things starts to get complicated on bigger projects and that's where simplicity comes in handy over nested spaghetti code.

I always prefer async/await as it's easy and I can easily avoid nesting issues plus benefit of try/catch.

Something like this for your code.

exports.login = async (req, res) => {
            const token = req.body.token;
            const client = new OAuth2Client(googleID, googleSecret);
            const ticket = await client.verifyIdToken({
                idToken: token,
                audience: googleID
            });

            const user = await User.findOne({
                "email": ticket.payload.email
            });

As you can see, so much cleaner and add try/catch to catch the bugs

  • Related