简体   繁体   English

在具有1个猫鼬查询的函数中使用async await很好吗?

[英]is it good to use async await in a function with 1 mongoose query?

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? 由于猫鼬返回诺言,但由于与异步,我只是感到困惑,但是在这里,它只是对db的1条查询? 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? 由于它是2个查询,因此您必须等待第一个查询,然后等待第二个查询,但是当您只需要等待1个查询时,它可以解决吗?

async functions will always return Promises, so there's really no need for async/await in the case of a single find(). 异步函数将始终返回Promises,因此在单个find()情况下,实际上不需要异步/等待。 Might as well do this: 也可以这样做:


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

...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM