Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

route in app.js

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading