Illysis Illysis - 1 year ago 65
Javascript Question

Promisified cicle inside promisified cicle in NodeJS

I'm having a problem with promises in NodeJS even thought I'm using Bluebird. In the following code:

var Promise = require('bluebird');
var google = require('utils/google');

// list of (max 60 * number of types defined) nearby places
var nearby_places = [];

Promise.each(config.type.nearby, function (type) {
google.nearbySearch(, request.query.lng, request.query.rad, type)
.then(function (places) {

// list of (max 60) places
var detailed_places = [];

console.log('Found ' + places.length + ' places.');

// Get full details of places and insert them into database
Promise.each(places, function (place_id) {
.then(function (res) {
.catch(function (err) {
.then(function () {
// Push detailed places to nearby places
nearby_places = nearby_places.concat(detailed_places);

.catch(function (err) {
}).then(function () {
// Returns (max 60 * number of types defined) nearby places
return reply(nearby_places);

It executes the
and prints somethings in there, so I know it's running. But when it ends, it doesn't waits for the inside
Promise.each(places, ...
. It goes directly to the
return reply(...
empty. Then, it shows me in the console
Found X places.

I don't think I fully understand Promises/Bluebird, but I don't know what I'm doing wrong.

Answer Source

The issue is that you do not return a Promise from .then() chained to google.nearbySearch(, request.query.lng, request.query.rad, type).

You should be able to resolve issue by returning Promise.each(places, function(){}) from .then() chained to initial google.nearbySearch(, request.query.lng, request.query.rad, type) call

return Promise.each(places, function(){})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download