【发布时间】:2016-05-25 10:28:24
【问题描述】:
我正在尝试使用 Promise 使事情变得简单,但它似乎是一个真正的噩梦。我想我错过了一些东西。
我愿意:
- 在数据库中获取一些文章
- 查看找到的每篇文章并遍历 article.authors 数组。
- 在每篇文章的数据库(包括 author.images)中获取每个作者
- 将第一步中的文章列表发回给客户,但使用 article.authors.images 进行了更新
我尝试了几种使用 Map / Each / spread / Reduce / _.clone / _cloneDeep 的方法
但没有什么能按预期工作
任何帮助将不胜感激
return Promise.bind({})
.then(function find_article(){
return Article.find().sort(req.params.sort).skip(req.params.page).limit(req.params.limit).populateAll()
}).then(function(articles){
dataBack = articles
var articlesPromise = Promise.map(articles,function(article){
console.log('------------');
var AuthorsPromise = Promise.map(article.authors,function(author){
return User.findOne(author.id).populateAll().then(function(){
})
})
return Promise.all(AuthorsPromise).then(function(data){
console.log('*******************************');
console.log(data);
return data
})
})
return Promise.all(articlesPromise).then(function(allArticles){
console.log('++++++++++++++++++++++++++++++');
console.log(allArticles);
})
})
.then(function(WhatIsInThere){
console.log('somethinAfter');
console.log(WhatIsInThere);
})
我得到了这样的东西,但仍然不起作用我仍然错过了 .all() 的要点
【问题讨论】:
-
您使用的是哪个数据库,这是相关的,因为一旦您的数据库开始增长,您构建查询的方式将杀死您的服务器
-
至于问题,将您的任务模块化为单独的步骤。第 1 步,使用包装在 Promise 中的数据库查询获取文章。第 2 步,函数使用 Promise.all 获取文章数组,并为每篇文章返回另一个模块化的 Promise.all,再次获取作者并在数据库查找时返回作者图像。顶级 api 将调用第一个模块,并链接其他模块
-
如果您已经使用过
Promise.map,则无需再拨打Promise.all。注意Promise.map(arr, f)等价于Promise.all(arr.map(f))
标签: javascript dictionary promise bluebird