【发布时间】:2017-08-20 04:04:04
【问题描述】:
我有一个博客,上面有一些帖子。
在 post 表中,我插入了带有 authorId 的帖子。
现在我想从另一个名为 user 的表中将所有 authorId 转换为 authorName。
为了进行转换,我使用了一个函数 getPostAuthor,它向主函数返回一个承诺。
但我无法使用 map 函数从 getPostAuthor 收集返回值
什么问题?
var db = require('../controllers/db');
var mongo = require('mongodb').MongoClient();
var url = "mongodb://localhost:27017/blog";
var ObjectId = require('mongodb').ObjectID;
//#1: this function lists all posts in my blog
const list = function(req, res){
db.find('post', {}, 10, {timeCreated: 1})
.then(posts => {
var promises = posts.map(post =>
getPostAuthor(post.author)
.then(author => author /* this value doesn't go to promises*/)
);
console.log(promises); //printed [Promise {<pending>}, ...]
})
}
//#2: this function gets authorId and gives authorName
const getPostAuthor = function(authorId){
return db.findOne('user', {_id: new ObjectId(authorId)})
.then(author => author.name);
}
//#3: finds from db
const find = function(collection, cond = {}, limit = 0, sort = {}){
return mongo.connect(url)
.then(db =>
db.collection(collection)
.find(cond)
.limit(limit)
.sort(sort)
.toArray()
)
}
//#4: finds one from db
const findOne = function(collection, cond = {}){
return mongo.connect(url)
.then(db =>
db.collection(collection).findOne(cond)
)
}
list();
【问题讨论】:
-
.then(posts => {没有返回任何东西......所以你已经在变量promises中构建了一个承诺数组......并丢弃了它 - 事实上,list函数本身什么都不返回,所以,不确定你对代码的期望是什么 -
你可能需要做
Promise.all(promises).then(results => { /* do something with the resolved promises here */}); -
在这一步中我只想要打印承诺并查看一组作者姓名
-
它们是承诺,您需要等待它们解决,请参阅第二条评论:p
-
tnx,这工作正常。
标签: javascript arrays asynchronous promise