mo30
mo30

Reputation: 89

how to pass promise to map

i have a blog and i've some posts on it.
in post table i inserted posts with authorId. and now i want to convert all authorId to authorName from another table that is called user.
to convert, i use a function getPostAuthor that returns a promise to main function.
but i can't collect returned value from getPostAuthor with map function
what is problem?

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();

Upvotes: 1

Views: 241

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

You need to wait for the promises you received using .map to resolve to see the values - like this:

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);
        });
    })
}

alternatively

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);
});

Upvotes: 1

Related Questions