json - Nodejs callback hell in foreach -
i have venues data. want how people in here after compress venues data , count data json. code working json result null.
var _venues = _.map(venues.response.venues, function (v) { checkin.where({ 'venuesuniqeid': v.id, 'createddate': { $gte: new date().gethours() - 2 } }) .count(function (err, herenow) { return new venue({ 'uniqeid': v.id, 'name': v.name, 'count': herenow }); }); }); return r.json(_venues);
first of all, understanding of map
function is: map takes set of inputs , 1-to-1 transform them different. in case, _venues
array empty because not returning inside _.map
callback.
the way have tackled problem use promises library bluebird
or q
, leverage .all
method. in case _.map not outputting actual _venues
_venuepromises
later execute , wait array of venues. in other words, because of asynchronous nature of mongoose, output of checkin.where
not collection of venues collection of promises.
disclaimer: not use mongoose not sure how integrates either q or bluebird.
var promise = require('bluebird'); var _venuepromises = _.map(venues.response.venues, function (v) { return checkin.where({ 'venuesuniqeid': v.id, 'createddate': { $gte: new date().gethours() - 2 } }) .count(function (err, herenow) { return new venue({ 'uniqeid': v.id, 'name': v.name, 'count': herenow }); }); }); promise.all(_venuepromises).then(function (actualvenues) { return r.json(actualvenues); });
Comments
Post a Comment