0
votes

I am just confused if it's good to use async await in such cases:

import User from models/User

export const getUser = async (_id) => {
  const user = await User.findOne({ _id })
  if (user) return user 
  return null 
}

export const getUser = async (_id) => {
   return await User.findOne({ _id })
}

Since mongoose return promise but I am just confused since with async, but here, it's only 1 query on db? unlike this:

export const getUser = async (_id) => {
   try { 
     const user = await User.findOne({ _id })
     const comments = await User.findOne({ _id })
     return { user, comments }
   } catch(e) {
     console.log('something went wrong', e)
     return null
   }
}

since it's 2 query then you have to await the 1st one then the 2nd, but when you have to await only 1 query, does it resolve?

1
Please clarify your question. async/await will wait for each time it's told to await. You can fire multiple promises off at once using Promise.all, but your question does not make sense. What do you mean by when you have to await only 1 query does it resolve? - Robert Mennell
I can't understand what you're asking, particularly with the question "does it resolve?" Both these methods could be improved, but I get the feeling that's not what you're confused about. - Patrick Roberts
i am confused if it's good to use: const getUser = (_id) => return User.findOne({ _id }) when you only have 1 promise in a function, in this case since Model query is promise - gpbaculio

1 Answers

2
votes

async functions will always return Promises, so there's really no need for async/await in the case of a single find(). Might as well do this:


export const getUser = (_id) => {
   return User.findOne({ _id })
}

...

getUser(aUserId).then(user => console.log(user))