【问题标题】:Nested async/await on Mongoose queries [duplicate]Mongoose查询上的嵌套异步/等待[重复]
【发布时间】:2020-09-11 02:19:28
【问题描述】:

我有一个async 函数需要返回一个user_ids 数组。我的代码是这样的:

async function getUserIds(option) {
  let user_ids = [];

  if (option === 'test') {
    const departments = await Departments.find({}).exec()
      .catch(() => console.log('ERROR');

    console.log('BEFORE LOOP');

    await departments.forEach(async(dpt) => {
      const pop = await Populations.findOne({_id: dpt.id}) 
        .catch(() => console.log('ERROR');

      console.log('work...');

      if (pop && (pop.max > pop.min)) {    
        const _users = await User.find({_id: {$in: pop.ids}}).exec()
          .catch(() => console.log("ERROR");

        user_ids = user_ids.concat(_users.map((u) => u._id));
        console.log('finished work...');
      }
    });

    return user_ids;
}

async function main() {
    let user_ids = await getUserIds('test');
    console.log(user_ids);
}

现在这总是返回一个空数组[],我可以看到控制台日志以异步方式:

BEFORE LOOP
[]   --> the return 
work...
work...
work...
work...
work...
work...
finished work...
finished work...
work...
finished work...
work...
finished work...
finished work...

我猜这行 await departments.forEach(async(dpt) => { 不是真的 "awaiting" 所以我能做什么,我做错了什么?

【问题讨论】:

  • await departments.forEach 这行什么都不做,用map 替换它并做await Promise.all([...])
  • 你成功了吗?

标签: node.js mongoose async-await


【解决方案1】:

async/await 是一种使用Promise 的糖方法。

async 类似于 new Promise(),await 类似于 .then()。

使用Promise.all() 等待所有 Promise 解决后再继续。

在您的情况下,您应该使用Array.prototype.map() 而不是Array.prototype.forEach()。 forEach() 返回 undefined 并且您正在使用 await。 .map() 将返回一个 Promise 数组:

// Using .map()
departments = [ Promise, Promise, Promise ] // await till all Promise resolves to go foward.

// Using .forEach()
departments = 'undefined' // nothing to await for.

await Promise.all(
        departments.map(async(dpt) => {
            const pop = await Populations.findOne({_id: dpt.id})
                .catch(() => console.log('ERROR');

            console.log('work...');

            if (pop && (pop.max > pop.min)) {    
                const _users = await User.find({_id: {$in: pop.ids}}).exec()
                    .catch(() => console.log("ERROR");

                user_ids = user_ids.concat(_users.map((u) => u._id));
                
                console.log('finished work...');
            }
       })
);

【讨论】:

    【解决方案2】:

    在从函数返回结果之前,您应该等待部门承诺。在您的情况下,forEach 行没有任何作用,请将其替换为 map 或 for of

    以map 为例

    ...
    const promises = departments.map(async(dpt) => {
      const pop = await Populations.findOne({_id: dpt.id}) 
        .catch(() => console.log('ERROR');
    
      console.log('work...');
    
      if (pop && (pop.max > pop.min)) {    
        const _users = await User.find({_id: {$in: pop.ids}}).exec()
          .catch(() => console.log("ERROR");
    
        user_ids = user_ids.concat(_users.map((u) => u._id));
        console.log('finished work...');
      }
    });
    
    await Promise.all(promises)
    
    return user_ids
    

    【讨论】:

      猜你喜欢
      • 2018-06-25
      • 2019-05-25
      • 2020-11-05
      • 1970-01-01
      • 2018-06-04
      • 2017-09-05
      • 2020-10-17
      • 2012-07-31
      • 1970-01-01
      相关资源
      最近更新 更多