我的代码是这样的
app.post('/get_page_data', function(req, res) {
function find (i,documents)
{
Item_data.find({item_name:documents[i].item_name}).exec(function (err,asd){
console.log(documents[i].item_name+": found");
console.log(asd[0].like);
}
)
}
Page_data.find().lean().exec(function (err, documents) {
var doc=documents;
async.series([
// 1st
function(done){
for(var i=0;i<documents.length;i++)
{
find(i,doc);
done()
}
},
// 2nd
function(done){
console.log("1");
console.log(doc);
console.log("2");
res.end(JSON.stringify(doc));
console.log("3");
done()
}
]);
}
)});
我简单介绍一下我的代码 当 ajax 调用/get_page_data 我将页面数据(page1,page2,page3 ...)放入文档中 每个页面都有一个 item_name 但页面数据没有“喜欢”数据 所以我通过相同的项目名称在另一个集合(Item_data)中找到“like”的值,并将“like”放在页面数据文档中
但这让我发疯 页面数据在我输入喜欢的值之前发送
所以我读到了关于非阻塞 io 和异步 blahblah... 我找到了异步模块。并使用了它。 但是正如您在上面的图片中看到的,它们不起作用
(在尝试异步模块之前它们都不起作用)
我不知道为什么res.end部分之前执行了,请告诉我这种情况的解决方案谢谢阅读
最佳答案
您的 find
函数正在进行异步调用,因此 done()
在返回任何数据之前被调用。
您应该将它移到内部查找回调中。
编辑:直接使用 async.each
而不是 async.series
。
app.post('/get_page_data', function(req, res) {
function find (document, cb) {
Item_data.find({item_name:document.item_name}).exec(function (err,asd) {
console.log(document.item_name+": found");
console.log(asd[0].like);
cb();
})
}
Page_data.find().lean().exec(function (err, documents) {
var doc=documents;
async.each(documents,
// 1st
find(document, cb),
// 2nd
function() {
console.log("1");
console.log(doc);
console.log("2");
res.end(JSON.stringify(doc));
console.log("3");
});
}
)});
PS:该代码中还有很多需要改进的地方。但这样它应该可以工作。
关于javascript - Node Js 模块 async.series 不工作(在函数执行之前的函数之前),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38163289/