gpt4 book ai didi

javascript - Sequelize Foreach 循环在更新数据之前发送响应

转载 作者:行者123 更新时间:2023-12-03 22:41:36 25 4
gpt4 key购买 nike

我正在尝试从帖子中获取所有内容和媒体,然后附加到新帖子以发送到响应以便轻松访问数据。问题是,每当我运行调用时,都会在获取内容和媒体之前发送响应。

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

};

最佳答案

记住您使用异步代码,正如您所说,您在 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

关于javascript - Sequelize Foreach 循环在更新数据之前发送响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41914443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com