蓝鸟承诺:循环猫鼬结果

Bluebird promise: loop over mongoose result

我通过 Mongoose(MEAN 环境)从 MongoDB 查询作者数据。作者数据还包含作者所写书籍的数组 (-> results.books)。收到后,我想遍历这一系列书籍并检查某些值。到目前为止,这是我的代码。

return Author.findOne({_id: req.user._id}, '-username').execAsync()
.then(function(results) {

return Promise.each(results.books) //this line causes TypeError rejection
}).then(function(book){     
   console.log('book:'+book); // test output
   if(book==='whatever‘){
      //do foo
   }  
}).catch(function(err){
    console.log('Error: '+err);
});

不幸的是,我无法让它工作,因为它一直给我上面标记的行的拒绝 TypeError。我尝试在此处应用此解决方案 (Bluebird Promisfy.each, with for-loops and if-statements?),但它不会成功,因为它似乎也是另一种问题。

Bluebird 的 Promise.each() 采用一个可迭代对象和一个迭代器回调函数,该函数将为可迭代对象中的每个项目调用。您没有传递回调函数。 Promise.each() 之后的 .then() 处理程序在整个迭代完成后被调用。看起来您希望它成为迭代器 - 事实并非如此。

Promise.each() 的 Bluebird 文档是 here

我不确定你到底想完成什么,但也许这就是你想要的:

return Author.findOne({_id: req.user._id}, 'username').execAsync()
   .then(function (results) {
        return Promise.each(results.books, function(book) {
            console.log('book:' + book); // test output
            if (book === 'whatever‘) {
               //do foo
            }
        });
    }).then(function() {
        // Promise.each() is done here
    }).catch(function (err) {
        console.log('Error: ' + err);
    });