Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在node.js和mongoose中返回多个异步/等待调用的结果_Node.js_Mongodb_Mongoose_Async Await - Fatal编程技术网

如何在node.js和mongoose中返回多个异步/等待调用的结果

如何在node.js和mongoose中返回多个异步/等待调用的结果,node.js,mongodb,mongoose,async-await,Node.js,Mongodb,Mongoose,Async Await,因此,我有一个函数,可以对MongoDB数据库进行一系列异步调用。我希望在完成所有调用后返回结果,但是下面的代码没有这样做 const getMatchesInfo = async mongoDBUserIds => { _.map(mongoDBUserIds, async mongoDBUserId => { const user = await UserCollection.findOne({ _id: mongoDBUserId

因此,我有一个函数,可以对MongoDB数据库进行一系列异步调用。我希望在完成所有调用后返回结果,但是下面的代码没有这样做

const getMatchesInfo = async mongoDBUserIds => {
    _.map(mongoDBUserIds, async mongoDBUserId => {
        const user = await UserCollection.findOne({
            _id: mongoDBUserId
        });
        console.log('user.profile.name = ', user.profile.name);

        return user;
    });
};
我在Node.js API中使用以下函数调用此函数:

module.exports = app => {
    app.get('/api/matches', requireLogin, async (request, response) => {
        const mongoDBUserIds = request.query.mongoDBUserIds.split(',');
        let matches_info = await getMatchesInfo(mongoDBUserIds); // <=== await here

        console.log('matches_info = ', matches_info);
        response.send(matches_info);
    });
};
module.exports=app=>{
app.get('/api/matches',requireLogin,异步(请求,响应)=>{
const mongoDBUserIds=request.query.mongoDBUserIds.split(',');

让matches_info=wait getMatchesInfo(mongoDBUserIds);//它与Mongoose无关,
\uMap()中的异步操作不会像您认为的那样工作

检查本文中的解释,它是关于数组#forEach(),但也适用于您的情况

这应该适合您:

const getMatchesInfo = async mongoDBUserIds => {
  const users = [];
  for (mongoDBUserId of mongoDBUserIds) {
    const user = await UserCollection.findOne({
        _id: mongoDBUserId
    });
    console.log('user.profile.name = ', user.profile.name);
    users.push(user);
  }
  return users;
};

顺便说一句,您没有在代码中返回
.map()
的结果。

这与Mongoose无关,
\u.map()
回调中的异步操作不会像您认为的那样工作

检查本文中的解释,它是关于数组#forEach(),但也适用于您的情况

这应该适合您:

const getMatchesInfo = async mongoDBUserIds => {
  const users = [];
  for (mongoDBUserId of mongoDBUserIds) {
    const user = await UserCollection.findOne({
        _id: mongoDBUserId
    });
    console.log('user.profile.name = ', user.profile.name);
    users.push(user);
  }
  return users;
};
顺便说一下,您没有在代码中返回
\uu.map()
的结果