基本上我想要做的是等待並獲得前兩個函數結果並將該值傳遞給第三個函數。因此,使用Node Q模塊,我嘗試了下面的代碼。節點JS從多個承諾獲取值
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();
EDIT
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;
}
然而此代碼不會返回其在第二然後代碼 「dropLocation」 定義的值,它返回爲未定義。你看到這裏有什麼問題嗎?
在此先感謝。
getAddressDetail是否返回承諾? –
是的,看到編輯。 –
您並未等待第二個'getAddressDetail'完成,這就是爲什麼'dropLocation'的問題開始未定義。 –