在javascript中将数组作为元素添加到数组中

在javascript中将数组作为元素添加到数组中,javascript,node.js,express,mongoose,Javascript,Node.js,Express,Mongoose,节点,快车,猫鼬 我试图将数组作为元素从回调添加到数组中 app.get('/view', function(req, res){ var csvRows = []; Invitation.find({}, function(err, invitations){ if(err){ console.log('error'); } else { invitations.forEach(function(invi

节点,快车,猫鼬

我试图将数组作为元素从回调添加到数组中

app.get('/view', function(req, res){
    var csvRows = [];
    Invitation.find({}, function(err, invitations){
       if(err){
           console.log('error');
       } else {

           invitations.forEach(function(invitation){
               Guest.find({_id: invitation.guests}, function(err, guest){
                   if(err){

                   } else {
                       var rsvpURL = 'url'+invitation._id;

                        var csvRow = [guest[0].firstName, 
                                    guest[0].addr1, 
                                   ...,
                                    rsvpURL];
                        csvRows.push(csvRow);

                   }
               });
           });
           console.log(csvRows);
           res.send(csvRows);
       }

    });
});

数组没有得到任何添加。如果您有任何想法,我们将不胜感激。

等待
承诺。所有
都将返回一个承诺,该承诺将解析为所需的行:

app.get('/view', function(req, res){
  Invitation.find({}, async function(err, invitations){
    if(err){
      console.log('error');
      return;
    }
    const csvRows = await Promise.all(invitations.map(function(invitation){
      return new Promise((resolve, reject) => {
        Guest.find({_id: invitation.guests}, function(err, guest){
          if(err){
            console.log('error');
            reject();
          }
          const rsvpURL = 'url'+invitation._id;
          const csvRow = [guest[0].firstName, guest[0].addr1, rsvpURL];
          resolve(csvRow);
        });
      });
    }));

    console.log(csvRows);
    res.send(csvRows);
  });
});

您正在尝试在异步操作完成之前返回数组。请尝试,谢谢!仅供阅读本文的其他人参考,请确保您正在使用node 7+实施此解决方案。