【问题标题】:Returning mongoose result to a variable将猫鼬结果返回到变量
【发布时间】:2019-01-31 19:05:39
【问题描述】:

我知道这是一个基本问题,但我无法弄清楚。我尝试了一些异步函数的回调,但它没有解决我的问题。所以这是我的代码。

Collection1.find({archived:false}).exec().then(obj => {

obj = _.groupBy(obj,'department');
Object.keys(obj).forEach(function(key) {

  const object_collection =[];

  function retrieveUser(callback) {
    for(let i = 0;i obj[key].length; i++){

      French.find(function(err, users) {
        if (err) {
          callback(err, null);
        } else {
          callback(null, users[0]);
        }
      });

    };
  };

  retrieveUser(function(err, user) {
    object_collection.push(user);
  });

  // i need object_collection here after for loop has done
  console.log(object_collection);


});

})

【问题讨论】:

    标签: node.js mongodb mongoose nosql


    【解决方案1】:

    这是我可以使用提供的详细信息做的事情。

    如果您使用的是 Node.js v7.6 或更高版本,您可以利用 async/await 的用法并让您更轻松,重构如下。

    async function yourFunctionName(req, res) {
        const obj = await Collection1.find({archived:false}).exec();
    
        obj = _.groupBy(obj, 'department');
    
        Object.keys(obj).forEach(key => {
            const object_collection = [];
            const frenchPromises = [];
    
            for (let i= 0; i <= obj[key].length; i ++) {
                // This will create an array of promises that will be resolved later.
                frenchPromises.push(
                    // This will do the same as your callback, but returning a promise.
                    French.find().exec().then(users => users[0])
                );
            }
    
            // When awaiting a Promise.all we will get an array containing the results
            // of all the promises insde the frenchPromises array.
            // Meaning, that we will get back the array of users from the previous code.
            object_collection = await Promise.all(frenchPromises);
    
            console.log(object_collection)
        });
    }
    

    如果不使用 async/await,这里也是一样的,但只有 Promises。

    const obj = Collection1.find({ archived: false })
        .exec()
        .then(obj => {
            obj = _.groupBy(obj, 'department');
            const frenchPromises = [];
    
            Object.keys(obj).forEach(key => {
                for (let i = 0; i <= obj[key].length; i++) {
                    // This will create an array of promises that will be resolved later.
                    frenchPromises.push(
                        // This will do the same as your callback, but returning a promise.
                        French.find().exec().then(users => users[0])
                    );
                }
            });
    
            // Returns an array of promises that will be resolved in the next .then() call
            return Promise.all(frenchPromises);
        }) // This will return the array of users
        .then(object_collection => {
            console.log(object_collection);
        });
    

    希望这会有所帮助。

    【讨论】:

    • 感谢您为此付出的努力。我已经用与此类似的方式解决了我的问题。我在“foreach”之后分配了“异步函数”,仅用于“for循环”并将返回值推送到数组。但我会牢记这一点!
    猜你喜欢
    • 2014-07-25
    • 1970-01-01
    • 2014-01-09
    • 2014-05-30
    • 2018-08-22
    • 2015-08-26
    • 1970-01-01
    • 2018-07-30
    相关资源
    最近更新 更多