[英]Nodejs Module async.series not working (later function excutes before previous function)
我的代碼是這樣的
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,但頁面數據沒有“like”數據,所以我找到了值其他集合中的“喜歡”(Item_data)由相同的項目名稱並在頁面數據文檔中放入“like”
但這讓我瘋狂的是,在我輸入類似值之前,頁面數據已被發送
所以我讀到了關於非阻塞io和async blahblah ......我找到了異步模塊。 並使用它。 但正如你可以看到上面的圖片,他們沒有工作
(在嘗試異步模塊之前,它們都沒有工作)
您的find
函數正在進行異步調用,因此在返回任何數據之前調用done()
。 你應該在內部的find回調中移動它。
編輯:直接使用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:你應該在這段代碼中改進很多東西。 但那樣它應該有效。
把完成的東西放在aysn函數里面並在索引值時調用done
app.post('/get_page_data', function(req, res) {
function find (i,documents,cb)
{
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);
console.log(i +"/"+ documents.length);
documents[i]["like"]=asd[0].like;
if(i==documents.length-1) cb();
//call done() when the index reached maximum
})
}
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); //put the done thing inside the function
}
},
// 2nd
function(done){
console.log("1");
console.log(doc);
console.log("2");
res.end(JSON.stringify(doc));
console.log("3");
done()
}
]);
好好工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.