向Mongo发送并行请求,并在所有请求完成后继续

时间:2019-09-10 21:02:08

标签: javascript node.js mongodb asynchronous async-await

我遇到MongoDb JavaScript请求的问题,首先我要检索帖子数组(1),然后我需要为每个帖子提出10个请求(2)以获得额外的数据,然后再完成其他工作(3)。

问题是我只找到按顺序1> 3> 2或按顺序1> 2> 2> .. 2> 2> 3运行的解决方案,该解决方案在2处等待以前的请求完成和新的一起去。

对我来说,最好的解决方案是立即解雇所有(2)个请求,当它们全部完成后,继续进行其余的工作(3),如下所示:1> 22 ... 22> 3。

async loadPosts() {
 const posts = await this._dbPosts.find({}, {limit: 10}).toArray()
 console.log(1)
 await posts.forEach(async post => {
  post.liked = await this._checkLikeOf(post)
 })
 console.log(3)
}

async _checkLikeOf(post) {
 const result = await this._dbLikes.findOne({id: this._auth.user.id, [`likes.${post._id}`]: true})
 console.log(2)
 return !!result
}

在这种情况下,发送_checkLikeOf()的所有请求而无需等待先前的请求完成,并且我的控制台日志为1> 3> 2。

async loadPosts() {
 const posts = await this._dbPosts.find({}, {limit: 10}).toArray()
 console.log(1)
 for (let workout of workouts) {
  workout.hearted = await this._checkHeartOf(workout)
 }
 console.log(3)
}

async _checkLikeOf(post) {
 const result = await this._dbLikes.findOne({id: this._auth.user.id, [`likes.${post._id}`]: true})
 console.log(2)
 return !!result
}

使用此解决方案,我得到了正确的订单,但是每次检查都像等待上一个一样。所以我得到1> 2> 2> ...> 2> 2> 3,这非常慢。

我正在寻找一种介于两者之间的解决方案,该解决方案可以获取所有帖子,然后发送所有10个请求进行检查,在完成所有10个请求之后,我想继续执行(3)

1 个答案:

答案 0 :(得分:1)

您可以通过Promise.all等待一系列的诺言

async loadPosts() {
 const posts = await this._dbPosts.find({}, {limit: 10}).toArray()
 console.log(1)
 await Promise.all(posts.map(post => this._checkLikeOf(post)))
 console.log(3)
}

async _checkLikeOf(post) {
 const result = await this._dbLikes.findOne({id: this._auth.user.id, [`likes.${post._id}`]: true})
 console.log(2)
 return !!result
}