2016-09-10 2 views
1

У меня проблема с обещаниями в NodeJS, даже я думал, что использую Bluebird. В следующем коде:Продвинутый cicle внутри promisified cicle в NodeJS

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.lat, 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) { 
       google.getPlaceDetails(place_id) 
        .then(function (res) { 
         detailed_places.push(res); 
        }) 
        .catch(function (err) { 
         console.log(err); 
        }); 
       }) 
       .then(function() { 
        // Push detailed places to nearby places 
        nearby_places = nearby_places.concat(detailed_places); 
       }); 

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

Он выполняет google.nearbySearch() и печатает нечто там, так что я знаю, что это работает. Но когда он заканчивается, он не ждет внутреннего Promise.each(places, .... Он идет непосредственно на return reply(... с nearby_places пустым. Затем он показывает мне в консоли Found X places..

Не думаю, что я полностью понимаю обещания/Bluebird, но я не знаю, что я делаю неправильно.

ответ

0

Вопрос в том, что вы не return a Promise от .then() прикованный к google.nearbySearch(request.query.lat, request.query.lng, request.query.rad, type).

Вы должны быть в состоянии решить проблему, возвращая Promise.each(places, function(){}) от .then() прикован к первоначальному google.nearbySearch(request.query.lat, request.query.lng, request.query.rad, type) позвонить

return Promise.each(places, function(){}) 
+0

Вам также может понадобиться для '' return' google.getPlaceDetails (place_id) '' изнутри .each() 'call, _" Если функция итератора возвращает обещание или последующее, то результат обещания ожидает, прежде чем продолжить следующую итерацию. "_ http://bluebirdjs.com/docs/api/promise.each.html – guest271314

+0

Мне также нужно было вернуть google.nearbySearch (... 'в дополнение к вашим ответам. Спасибо! – Illysis

Смежные вопросы