javascript - how to pass promise to map -
i have blog , i've posts on it.
in post table inserted posts authorid. , want convert authorid authorname table called user.
convert, use function getpostauthor returns promise main function.
can't collect returned value getpostauthor map function
problem?
var db = require('../controllers/db'); var mongo = require('mongodb').mongoclient(); var url = "mongodb://localhost:27017/blog"; var objectid = require('mongodb').objectid; //#1: function lists posts in 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 /* value doesn't go promises*/) ); console.log(promises); //printed [promise {<pending>}, ...] }) } //#2: function gets authorid , gives authorname const getpostauthor = function(authorid){ return db.findone('user', {_id: new objectid(authorid)}) .then(author => author.name); } //#3: finds 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 1 db const findone = function(collection, cond = {}){ return mongo.connect(url) .then(db => db.collection(collection).findone(cond) ) } list();
you need wait promises received using .map resolve see values - 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 /* value doesn't go promises*/) ); console.log(promises); //printed [promise {<pending>}, ...] // ********* 3 lines added 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 /* value doesn't go promises*/) ); console.log(promises); //printed [promise {<pending>}, ...] // *** added line below return promise.all(promises); }) }
...
list().then(authors => { console.log(authors); });
Comments
Post a Comment