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

问题描述 投票:1回答:1

节点,表达,猫鼬。

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

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

    });
});

数组没有添加任何东西。任何想法将不胜感激。

javascript node.js express mongoose
1个回答
1
投票

在每个找到的客人等待Promise.all,返回一个解析为所需行的承诺:

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);
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.