我尝试从帖子中获取所有内容和媒体,然后附加到新帖子以发送到响应以便于访问数据。问题是每当我运行呼叫时,都会在获取内容和媒体之前发送响应。
module.exports.getPosts = function(req,res){
var resultPosts = [];
Post.findAll({where:{UserUsername:req.headers.x_username}}).then(function(posts){
posts.forEach(function(post){
Db.getContent(post.id,function(foundContent){
Db.getMedia(post.id,function(foundMedia){
console.log('creating new post');
var newPost = {
id:post.id,
time:post.time,
username:post.UserUsername,
content: foundContent,
media:foundMedia
};
resultPosts.push(newPost);
});
});
});//foreach
console.log('sending');
res.send({posts:resultPosts});
});//end query
};
答案 0 :(得分:0)
记住你使用异步代码,正如你所说,你在getMedia回调完成工作之前调用res.send。将res.send移动到该回调,以确保在完成推送到resultPosts数组后调用它
module.exports.getPosts = function(req,res){
var resultPosts = [];
Post.findAll({where:{UserUsername:req.headers.x_username}}).then(function(posts){
posts.forEach(function(post){
Db.getContent(post.id,function(foundContent){
Db.getMedia(post.id,function(foundMedia){
console.log('creating new post');
var newPost = {
id:post.id,
time:post.time,
username:post.UserUsername,
content: foundContent,
media:foundMedia
};
resultPosts.push(newPost);
console.log('sending');
res.send({posts:resultPosts});
});
});
});//foreach
});//end query
答案 1 :(得分:0)
您必须使整个功能异步。在这种情况下,您必须先forEach通过所有结果,然后输出到res。您可以使用async.forEach()方法解决此问题:https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
我将使用迭代器执行一个简单的异步递归函数,使其完全保持本机状态,而无需任何额外的库。
var resultPosts = []
Post.findAll({where:{UserUsername:req.headers.x_username}}).then(function(posts)
{
getPost(posts[Symbol.iterator]())
function getPost(iter) {
var cursor = iter.next()
if(cursor.done)
return res.send({posts:resultPosts})
Db.getContent(post.id,function(foundContent){
Db.getMedia(post.id,function(foundMedia){
var post = cursor.value
resultPosts.push({
id:post.id,
time:post.time,
username:post.UserUsername,
content: foundContent,
media:foundMedia
})
getPost(iter)
}
})
})