基本上我想要做的是等待并获得前两个函数结果并将该值传递给第三个函数。因此,使用Node Q模块,我尝试了下面的代码。
getAddressDetail("", 51.528308, -0.3817812).then(function (pickupLoc) {
return pickupLoc.location;
}).then(function (pickupLocation) {
var drop = getAddressDetail(, 51.528308, -0.3817812);
return [pickupLocation,drop.location];
})
.then(function (pickupLocation, dropLocation) {
console.log("#####" + pickupLocation +"$$$" + dropLocation)
})
.done();
修改
function getAddressDetail(location = "", lat, long) {
var deferred = Q.defer();
var getLocation = "";
if (location == '' || location == 'undefined') {
var url = 'https://maps.googleapis.com/maps/api/geocode/json?key={APIKEY}&latlng=' + lat + ',' + long + '&sensor=false';
request({
url: url,
json: true
}, function(error, response, body) {
if (!error && response.statusCode === 200) {
getLocation = body.results[0].formatted_address;
deferred.resolve({
'location': getLocation
});
//console.log("*******" + getLocation);
}
})
} else {
getLocation = location;
deferred.resolve({
'location': getLocation
});
}
return deferred.promise;
}
但是,此代码不会返回在第2个代码" dropLocation"中定义的值,它将返回为undefined。你在这里看到任何问题吗?
提前致谢。
答案 0 :(得分:2)
您的代码中发生了一些狡猾的事情。
return [pickupLocation,drop.location]
会在下一个处理程序中生成1个参数(数组),因此您应该使用.then(function (pickupLocation, dropLocation) {})
.then(function (results) {})
var drop = getAddressDetail(, 51.528308, -0.3817812);
看起来不是承诺,因为您可以立即从结果中获取位置。 (return [pickupLocation,drop.location];
)那么为什么不在下一个处理程序中获取此值?
如果getAddressDetail()返回一个promise,只需编写一个promises数组并使用.spread()
操作,因为第二个promise中不需要第一个promise的结果。
一个例子;
var promiseArray = [];
promiseArray.push(getAddressDetail("", 51.528308, -0.3817812));
promiseArray.push(getAddressDetail("", 51.528308, -0.3817812));
Q.spread(promiseArray, function(pickupLocation, drop){
// first parameter (pickupLocation) = result of first promise
// second parameter (drop) = result of second promise
});