1

Node, express, mongoose.

I am trying to add an Array as an element to an Array from a callback.

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

    });
});

The array gets nothing added to it. Any thoughts will be greatly appreciated.

2
  • 1
    You're trying to return the array before the asynchronous operations have finished. Commented Apr 23, 2018 at 23:38
  • Try caolan.github.io/async/docs.html#map Commented Apr 23, 2018 at 23:40

1 Answer 1

1

Await the Promise.all over each found guest, returning a promise that resolves to the desired row:

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);
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! FYI to anyone else reading this make sure you are using node 7+ to implement this solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.