本文介绍了如何等待猫鼬.exec函数完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对异步的Node.js和Mongoose感到有些困惑.简而言之,我要发布一个用户名数组,并检查用户名是否在数据库中,然后将其放在valid数组中,否则,将其放在invalid数组中.

I am some cofused by asychronous nodejs and mongoose. Simplily, I want to post an array of usernames and check, if a username is in database, then I put it in the valid array, otherwise, put it in the invalid array.

这是我当前的代码:

var User = require('../../db/models/user');

api.post('/userlist', function(req, res) {

  var invalid = []; // usernames which can not be found in database
  var valid = []; // usernames which can be found in database

  (req.body.userlist).forEach(function(username) {

    User
      .findOne({username: username})
      .exec(function(err, user) {

        if (err) {
          res.send(err);
          return;

        } else if (!user) {

          invalid.push(username);

        } else {

          valid.push(req.params.item);
        }
      });
  });

  res.send({
    Invalid: invalid,
    Valid: valid
  });

});

当我执行上面的代码时,它直接输出初始空数组.

When I executed the above code, it outputs the intial empty array directly.

Invalid: [],
Valid: []

我知道这是因为nodejs首先执行此res.send然后执行功能.exec(function(err, user),但是我不知道如何获得正确的invalidvalid数组,请告知.

I know it is because nodejs first execute this res.send then execute function .exec(function(err, user), but i do not know how to get the right invalid and valid array, pls advise.

推荐答案

您最好的选择是使用诺言:

Your best bet is to use a promise:

api.post('/userlist', (req, res) => {
    // Takes a username and returns a promise for information on that username.
    function findByUsername(username) {
        return new Promise((resolve, reject) =>
            User.findOne({username}).exec((err, user) =>
                err ? reject(err) : resolve(user)
            )
        );
    }

    // Iterate the array and transform each user to a promise for data on that user.
    Promise.all(req.body.userlist.map(findByUsername))
        // Then, when all of the promises in that new array resolve
        .then(allUserDataInOrder => {
            // Find all the valid ones (if (user))
            let Valid = allUserDataInOrder.filter(Boolean); // Only those who are truthy
            // And all the invalid ones (if (!user))
            let Invalid = allUserDataInOrder.filter(userData => !userData); // Sadly, no convenient function here :(
            // And send both away
            res.send({Valid, Invalid}); // Short syntax FTW!
        })
        .catch(res.send); // Called with error object if any.
});

这篇关于如何等待猫鼬.exec函数完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 23:26