我想打電話給使用無極這樣的谷歌地圖地理編碼API返回的值:從無極
function makeGeoCodingRequest(address,bounds)
{
/*
Input parameters:
address:a string
bounds: an object of class google.maps.LatLngBounds(southWest,northEast)
This will return a set of locations from the google geocoding library for the given query
*/
var url="https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=AIzaSyD9GBloPC20X-1kWRo7sm_0z5xvCiaSd3c";
var promise,response;
var messages={
"ZERO_RESULTS":"No results were found",
"OVER_QUERY_LIMIT":"We are over the query limit.Wait awhile before making a request",
"REQUEST_DENIED":"Request was denied,probably using a bad or expired API Key",
"INVALID_REQUEST":"Request was sent without the required address,component or component",
"UNKNOWN_ERROR": "There was an error somewhere on Google's servers"
};
if(address)
promise=Q($.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=API_KEY"
}));
return promise.then(function(data) {
if (data.status === "OK") return data;
else console.error(messages[data.status]);
return null;
});
}
當我調用該函數makeGeoCodingRequest
要求,我發現我得到一個承諾,而不是值:
var geo=makeGeoCodingRequest(address);
console.log(Q.isPromise(geo));//returns true
爲什麼在返回值之前未執行promise.then?我如何從這個承諾中獲得價值而不是另一個承諾?
如果我拒絕使用'promise.then(...)'和'return promise',然後使用'makeGeoCodingRequest(address,bounds).then(...)',它會不會相同? – vamsiampolu 2014-08-27 15:15:49
是的,'makeGeoCodingRequest'返回的promise與''promise.then'處理程序中的返回值具有相同的值。你可以通過返回類似'Q.reject(新錯誤(「Http請求失敗」+ data.status))' – 2014-08-27 15:23:12
謝謝你的答案,一切正常,包括Q.reject。 – vamsiampolu 2014-08-27 15:40:02