简体   繁体   English

Javascript:需要帮助了解 mongooseODM 的异步/等待

[英]Javascript: Need help understanding async/await with mongooseODM

const deleteTaskCount = async(id) => {
const task = Task.findByIdAndDelete(id);
const count = await Task.countDocument({completed:false})
return count;

}

deleteTaskCount("1234").then((count)=>{
console.log(count);
})

I understood that with await in const task = Task.findByIdAndDelete(id);我明白在const task = Task.findByIdAndDelete(id);中等待it deletes the user with the id.But without the await keyword(like in the above function) the function still happens, that is it deletes the user but in a non-blocking way after some time.When i ran the above code the count is showing properly but the const task = Task.findByIdAndDelete(id);它使用 id 删除用户。但是没有 await 关键字(如在上面的函数中),function 仍然会发生,也就是说它会在一段时间后以非阻塞方式删除用户。当我运行上面的代码时,计数显示正确,但const task = Task.findByIdAndDelete(id); is not deleting the user.没有删除用户。

You should use await for the Task.findByIdAndDelete(id) as well.您也应该对Task.findByIdAndDelete(id)使用await When you use await , NodeJS will go do some other things until that resolves, and it will only then continue to execute the function (it will not block your code at all).当您使用await时,NodeJS 将 go 做一些其他事情直到解决,然后它才会继续执行 function (它根本不会阻止您的代码)。

const deleteTaskCount = async(id) => {
  const task = await Task.findByIdAndDelete(id);
  const count = await Task.countDocument({completed:false})
  return count;
}

deleteTaskCount("1234").then((count)=>{
  console.log(count);
})

I don't know much about the mongoose API but I suspect mongoose.query behaves similar to mongo cursors and many other asynchronous database drivers/ORMs.我不太了解 mongoose API 但我怀疑 mongoose.query 的行为类似于 mongo 游标和许多其他异步数据库驱动程序/ORM。 Queries often don't execute unless awaited or chained upon.除非等待或链接,否则查询通常不会执行。

In any case, without awaiting Task.findByIdAndDelete , there's no guarantee in concurrency between the two queries.在任何情况下,如果不等待Task.findByIdAndDelete ,就不能保证两个查询之间的并发性。 If you want the result of countDocument to reflect the changes in findByIdAndDelete , you must wait on the client-side for that query to complete and then run countDocument .如果您希望findByIdAndDelete的结果反映countDocument中的更改,您必须在客户端等待该查询完成,然后运行countDocument

You would achieve this by adding the await keyword before Task.findByIdAndDelete .您可以通过在Task.findByIdAndDelete之前添加await关键字来实现这一点。

I'd presonally recommend using the promises/thenables as opposed to await/async .我个人建议使用promises/thenables而不是await/async

Task.findByIdAndDelete("1234")
  .then(task => Task.countDocument({completed:false}))
  .then(count => console.log(count));

Imho, it's cleaner, less error prone, more functional, less confusing.恕我直言,它更干净,更不容易出错,更实用,更不容易混淆。 YMMV YMMV

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

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