用bluebird Promise时遇到的问题,无法执行到all()后的then()
具体表现就是,findTagPromise.then(getTagIdList, console.log).all(promises).then(renderRes, console.log);
,all这一步的完成了,然后就卡住,一直执行不到后一个then上。
希望能有高人指点,谢谢
bluebird API地址: http://bluebirdjs.com/docs/api-reference.html
app.get('/tag/:tagName', function(req, res, next) {
var pageInfos = [];
var promises = [];
var tmp;
console.log('begin');
var findTagPromise = Tag.findOne({name: req.params.tagName}, 'pages').exec(
function(err, pages) {
console.log(pages);
tmp = pages;
}
);
function getTagIdList(err, page) {
console.log('getTagIdList');
return new Promise(function(resolve, reject) {
tmp.pages.forEach(function(pageId) {
promises.push(Page.findOne({_id: new ObjectId(pageId)}, 'title').exec(function(err, page) {
if (err) return err;
console.log('all');
console.log(page);
pageInfos.push({
_id: pageId,
title: page.title
});
}));
});
resolve();
});
}
function renderRes(resolve, reject) {
console.log('renderRes');
return new Promise(function() {
res.render('index', {
pages: pageInfos
});
resolve();
});
}
findTagPromise.then(getTagIdList, console.log).all(promises).then(renderRes, console.log);
});
输出结果是: begin { pages: [ 564ae326168a71305daafb62 ], _id: 564ae326168a71305daafb63 } getTagIdList all { title: ‘zzzz’, _id: 564ae326168a71305daafb62 }
1 回复
getTagIdList 里resolve(promises)