用bluebird Promise时遇到的问题,无法执行到all()后的then()
发布于 9 年前 作者 CauT 4742 次浏览 最后一次编辑是 8 年前 来自 问答

具体表现就是,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)

回到顶部