我试图找到价值投2模型Res.send功能Model.find()之前进行的NodeJS
.get(function(req, res) {
var sellerPosts = [];
Product.find({seller_id : req.params.seller_id}, function(err, products) {
if (err) throw err;
for (var i = 0; i < products.length; i++) {
console.log("id", products[i].id);
Post.find({product_id : products[i].id}, function(err, posts) {
if (err) throw err;
for (var j = 0; j < posts.length; j++) {
sellerPosts.push(posts[j]);
console.log("in find",sellerPosts);
}
});
console.log(sellerPosts);
}
console.log("test", sellerPosts);
res.send(sellerPosts);
});
})
这是日志的问题时:
App listening on port 3000!
Connected to database
id 58ea96464429aa154cb8c43a
[]
id 58ed3171a0cc7f20f4c74c1c
[]
test []
in find [ { _id: 58ed28b8993a2317e41fc742,
product_id: 58ea96464429aa154cb8c43a,
phone: 9123123,
address: 'hanhitie17',
other: 'no others',
__v: 0 } ]
in find [ { _id: 58ed28b8993a2317e41fc742,
product_id: 58ea96464429aa154cb8c43a,
phone: 9123123,
address: 'hanhitie17',
other: 'no others',
__v: 0 },
{ _id: 58ed33cea0cc7f20f4c74c1d,
product_id: 58ed3171a0cc7f20f4c74c1c,
phone: 9123123,
address: 'hanhitie17',
other: 'no others',
__v: 0 } ]
第一sellerPosts仍然打印出真正的值,但“测试”日志是空的。 做了一些日志。我认为这是因为在Product.find()中的第一个之后,程序运行res.send,然后运行Post.find()。 请帮我解决这个问题,请!!!!
你应该看一看节点的'async'模块,尤其是'async.each'(http://caolan.github.io/async/) – devnull69
或只是调用'res.send'当你的回调里面有'i === products.length'时。异步模块效果很好,承诺也如此,但在使用这些软件包之前,您应该知道控制流程的工作原理。 – richardpringle