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

标签 javascript node.js express mongoose

Node 、 express 、 Mongoose 。

我正在尝试从回调中将数组作为元素添加到数组。

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

    });
});

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

最佳答案

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

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

关于javascript - 将数组作为元素添加到javascript中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49991348/

相关文章:

javascript - 如何保护应用程序免受第 3 方 js 库中存在的 XSS 向量的攻击?

javascript - 以编程方式显示表单默认验证状态

javascript - 对从数据库检索的数据进行分页后,模式窗口将不会打开

javascript - django-Angular,显示伺服器端错误

node.js - 亚搏体育appCI : How can I reuse installed npm packages between jobs?

node.js - Mongodb查询加入两个集合

javascript - 无法加载资源:net::ERR_CONNECTION_RESET Node js 服务器

jquery - 如何使用 JQuery 将评论从评论部分推送到数组中?

node.js - 跟踪链接的点击位置node.js

node.js - k8s 中端口未接收到 fetch 请求