从Promise返回一个值

vam*_*olu 9 javascript ajax jquery promise q

我想使用这样的Promise来调用Google Maps Geocoding 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;    
        });
}
Run Code Online (Sandbox Code Playgroud)

当我调用函数makeGeoCodingRequest请求时,我发现我获得了一个promise而不是一个值:

 var geo=makeGeoCodingRequest(address);
 console.log(Q.isPromise(geo));//returns true
Run Code Online (Sandbox Code Playgroud)

为什么不承诺.然后在返回值之前执行?我怎样才能从这个承诺中获得价值而不是另一个承诺?

Wil*_*eer 6

如果您依赖承诺以返回数据,则必须从函数返回承诺.

一旦你的callstack中的1个函数是异步的,如果你想继续线性执行,那么想要调用它的所有函数也必须是异步的.(async =返回一个承诺)

请注意,您的if语句没有大括号,因此只有条件失败后才会执行第一个语句.

我在这个例子中修复了它.请注意我添加的评论.

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) {
        // whatever you return here will also become the resolve value of the promise returned by makeGeoCodingRequest
        // If you don't want to validate the data, you can in fact just return the promise variable directly
        // you probably want to return a rejected promise here if status is not what you expected
        if (data.status === "OK") return data;
            else console.error(messages[data.status]);
        return null;    
    });
}
Run Code Online (Sandbox Code Playgroud)

您必须makeGeoCodingRequest以下列方式致电.

makeGeoCodingRequest(address,bounds).then(function(data){
    // this will contain whatever 
    console.log(data);
});
Run Code Online (Sandbox Code Playgroud)