【发布时间】:2020-04-24 08:10:15
【问题描述】:
如何使用 promise.all 和这个函数:
function getUsersGroups(users, req) {
users.forEach(function(user) {
user.groups = [];
db.collection("groups")
.find({ "users._id": String(user._id) })
.toArray(function(err, docs) {
user.groups = docs;
});
});
return users;
}
我不知道该怎么做,谢谢。
PS:用户数组没有通过文档实现(他们控制台日志正常)。
这是我的第二次尝试:
function getUsersGroups(users, req) {
users.forEach(
(user, index, array) => (
array[index].user =[]
array[index].user.groups = myApiCall(user))
);
function myApiCall(user) {
db.collection("groups")
.find({ "users._id": String(user._id) })
.toArray(function(err, docs) {
console.log(docs);
return docs;
});
}
return users;
}
array[index].user.groups = myApiCall(user))
^^^^^
SyntaxError: Unexpected identifier
编辑:
所以最后,我正在使用这个功能,就像 Ashish 所说的(它获取用户所在的所有组,并更新用户模型):
async function getUsersGroups(users, req) {
await Promise.all(users.map(user => {
return db.collection("groups")
.find({ "users._id": String(user._id) })
.toArray()
.then(group => {
user.groups = group;
})
}));
return users;
}
我在另一个 node.js 函数中这样调用:
getUsersGroups(docs, req)
.then(users => {
res.send(users);
})
.catch(error => {
// if you have an error
});
非常感谢!
【问题讨论】:
-
这与
node-mongodb-native有关吗? -
是的,有多个 api 调用。
-
这能回答你的问题吗? Node JS Promise.all and forEach
标签: javascript node.js es6-promise node-mongodb-native