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?
async/await
will wait for each time it's told toawait
. You can fire multiple promises off at once using Promise.all, but your question does not make sense. What do you mean bywhen you have to await only 1 query does it resolve?
- Robert Mennell