【发布时间】:2015-05-29 16:32:48
【问题描述】:
我正在使用 NodeJS 和 Async api 创建一个返回故事列表的 api 函数。 get 可以是浅的(仅包含引用其他对象的对象 ID)或深的(通过将 ID 替换为它所引用的对象来取消引用所有 ID 引用)。浅层 get 工作正常,但是当我运行深层副本时,它挂起。你可以在我的回调中看到我放置了console.log(#) 来记录触发了哪个回调,但没有一个被触发。
如果我弄错了 async 如何处理 .each、.serial 和 .parallel 函数的回调函数参数,我觉得问题就在于此。我需要一个函数,它会在异步完成所有任务后被触发,但是在每次操作(串行或并行完成)之后调用回调函数。
router.get('/stories', function(req, res, next) {
var db = req.db,
options = {
deep : req.query.deep != null ? parseInt(req.query.deep) : false,
offset : req.query.offset || 0,
limit : req.query.limit || 0
};
Story.listStories(db, options, function(err, stories){
if (!options.deep){
res.json(new Response(err, stories));
res.end();
}else{
if (err || stories == null){
res.json(new Response(err, null));
res.end();
return;
}
async.each(stories,
function(story, cb1){
var articles = [],
galleries = [];
async.series([
function(cb2){
async.parallel([
//Extract the story's articles and their outlets
function(cb3){
async.each(story.articles,
function(article_id, cb4){
Article.getArticle(db, article_id, function(err, article){
if (err){
cb4(err);
return;
}
Outlet.getOutlet(db, article.outlet, function(err, outlet){
if (err){
cb4(err);
return;
}
article.outlet = outlet;
articles.push(article);
});
});
},
function(err){console.log(4);
if (err)
cb3(err);
});
}
],
function(err){console.log(3); //Parallel callback
if (err)
cb1(err);
});
},
function(cb2){
story.articles = articles;
}
],
function(err){console.log(2);
if (err)
cb1(err);
});
},
function(err){console.log(1);
res.json(new Response(err, stories));
res.end();
}
);
}
});
});
【问题讨论】:
标签: javascript node.js asynchronous callback