我对NodeJS中的承诺有疑问,甚至认为我使用的是Bluebird。在以下代码中:
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.
中显示我。
我不认为我完全理解Promises / Bluebird,但我不知道我做错了什么。
答案 0 :(得分:0)
问题在于,return
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)
来电{1}来回复return Promise.each(places, function(){})
来解决问题
using namespace <your_library_namespace>;