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

标签 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)

最佳答案

您可以使用 Promise.all 等待一系列 promise

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
}

关于javascript - 向 Mongo 发送并行请求,并在所有请求完成后继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57878168/

相关文章:

node.js - 将标准输出重定向到文件 nodejs

mysql - YCSB清理阶段

javascript - Dropbox:MIME 类型 ('text/html' ) 不可执行,并且已启用严格 MIME 类型 > 检查

node.js - nginx 有时响应 504/502 网关超时错误

javascript - 无法让 componentDidUpdate() 停止循环

javascript - 使用 Node 和 ejs 时调用外部 api 端点并获取用户的详细信息

mongodb - 我可以/应该在 Mongoose 中索引嵌入的文档吗?

MongoDB 文件太大

javascript - 如何从 Chrome 扩展程序下载公共(public) Google Drive 文件?

javascript - 使用 mathJS 的 SumProduct 多维数组