为什么即使在使用async等待多个呼叫后仍然得到空响应? [英] Why even after using async await for multiple calls still got empty response?
本文介绍了为什么即使在使用async等待多个呼叫后仍然得到空响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是调用异步api
的简单节点路由.
Here is simple node route in which calling an asynchronous api
.
循环后需要的是return data
.但是它正在返回空白对象.
What needed is to return data
after the looping. But It is returning blank object.
try {
const array = ["brunch", "lunch", "crunch"]
const data = {}
array.map(async(d) => {
const venue = await Venue.find({ "category": { "$in": [d] }})
data[d] = venue
})
return data
} catch(err) {
throw err
}
请帮助我实现这一目标
推荐答案
有一种更好的方法可以通过MongoDB获得所需的结果,而无需循环,请使用聚合框架,在该框架中,您可以运行以下使用的管道> $facet
as
There is a better way to get the desired result with MongoDB and no need to loop, use the aggregation framework where you can run the following pipeline which uses $facet
as
try {
const array = ["brunch", "lunch", "crunch"]
const facet = array.reduce((acc, cur) => {
acc[cur] = [{ "$match": { "category": cur } }]
return acc
}, {})
const pipeline = [
{ "$match": { "category": { "$in": array } } },
{ "$facet": facet }
]
const results = await Venue.aggregate(pipeline).exec()
const data = results[0]
return data
} catch(err) {
throw err
}
您还可以按类别键和 $push
每个组中的文档,然后将其转换为 $arrayToObject
You can also group the documents by the category key and $push
the documents per group and then convert into keys of a document in a $replaceRoot
with $arrayToObject
try {
const array = ["brunch", "lunch", "crunch"]
const pipeline = [
{ "$match": { "category": { "$in": array } } },
{ "$group": {
"_id": "$category",
"data": { "$push": "$$ROOT" }
} },
{ "$group": {
"_id": null,
"venues": {
"$push": {
"k": "$_id",
"v": "$data"
}
}
} },
{ "$replaceRoot": {
"newRoot": { "$arrayToObject": "$venues" }
} }
]
const results = await Venue.aggregate(pipeline).exec()
const data = results[0]
return data
} catch(err) {
throw err
}
这篇关于为什么即使在使用async等待多个呼叫后仍然得到空响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文