DEV Community

Discussion on: OAuth 2.0 with Google API in Node.js

Collapse
epranka profile image
Edvinas Pranka

Nice and simple. Just one advice: Why are you not using the ES6 async/await? Your "Step 2 and 3" can look like:

 function async getUserDetails(code) {
   const {tokens} = await Oauth2Client.getToken(code);
   await Oauth2Client.setCredentials(tokens);
   return oauth2.userinfo.get({auth: Oauth2Client});
 } 
Enter fullscreen mode Exit fullscreen mode

Good luck!

Collapse
nipeshkc7 profile image
Arpan Kc Author

Thanks for your feedback. Honestly did not know how async-await worked, but did a bit of research and I edited the code to incorporate them.

 function async getUserDetails(code) {
   const {tokens} = await Oauth2Client.getToken(code);
   Oauth2Client.setCredentials(tokens);
   const usr_info = await oauth2.userinfo.get({auth: Oauth2Client});
   return usr_info;
 } 

A minor change from your suggestion, as .setCredentials() isn't async to my knowledge and I think userinfo.get() is. Feel free to correct me if I'm wrong.

Again thanks for your suggestion and will update the post accordingly.

Collapse
epranka profile image
Edvinas Pranka

I think it's ok. Async/Await is an amazing ES6 feature, keep going with that. You might forget about the callback hell.

And one more thing. Await can be used with the sync functions. It just does nothing if you make a mistake. E.g.


const asyncMethod = () => {
   return new Promise(resolve => {
      setTimeout(() => resolve('Hello'), 1000);
   });
}

const syncMethod = () => {
   return 'World';
}

function async greeting = () => {
   const hello = await asyncMethod();
   // below await is not needed, but it works too
   const world = await syncMethod(); 
   console.log(hello, world); // logs Hello World
}

Of course, you don't have to put await anywhere, but if you don't know if the function is async or sync just put it and you will be right.

Good luck!