【问题标题】:How to return the result of multiple async/await calls in node.js and mongoose如何在 node.js 和 mongoose 中返回多个 async/await 调用的结果
【发布时间】:2018-09-05 06:43:35
【问题描述】:

所以我有一个函数可以对 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);
    });
};

我不明白为什么matches_info 在函数getMatchesInfo 内部的console.logs 之前被打印出来?我认为await here 应该阻止它下面的代码运行,直到getMatchesInfo 返回。我不明白什么?

【问题讨论】:

    标签: node.js mongodb mongoose async-await


    【解决方案1】:

    这与 Mongoose 无关,_.map() 回调中的异步操作不会像你想象的那样工作。

    查看question 中的解释,它是关于 Array#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() 的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-18
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-20
      相关资源
      最近更新 更多