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/