我有一个博客,上面有一些帖子。
在帖子表中,我插入了具有authorId的帖子。
现在我想从另一个称为用户的表中将所有authorId转换为authorName。
要进行转换,我使用一个函数getPostAuthor,该函数将诺言返回给主函数。
但我无法使用地图功能从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();
最佳答案
您需要等待使用.map收到的承诺才能解析以查看值,如下所示:
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>}, ...]
// ********* 3 lines added to your code here
Promise.all(promises).then(authors => {
console.log(authors);
});
})
}
或者
const list = function(req, res){
// added return below
return 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>}, ...]
// *** added line below
return Promise.all(promises);
})
}
...
list().then(authors => {
console.log(authors);
});