Возврат результата Мангуста в переменную - PullRequest
0 голосов
/ 31 января 2019

Я знаю, что это основной вопрос, но я не могу понять это.Я пытался что-то с обратным вызовом для асинхронных функций, но это не решает мою проблему.Так вот мой код.

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);


});

})

1 Ответ

0 голосов
/ 31 января 2019

Это то, что я могу сделать с предоставленными подробностями.

Если вы используете 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, то же самое, но только с обещаниями.

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);
    });

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...