从无极返回值无极、返回值

2023-09-10 16:51:03 作者:华晨宇的优质女友

我想打电话给使用这样的承诺的谷歌地图API地理编码:

I would like to call the Google Maps Geocoding API using a Promise like this:

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 要求,我发现我得到一个承诺,而不是一个值:

When I call the function makeGeoCodingRequest request,I find that I obtain a promise instead of a value:

 var geo=makeGeoCodingRequest(address);
 console.log(Q.isPromise(geo));//returns true

为什么心不是前值执行promise.then被退回?我怎样才能获得一个值,从这个承诺,而不是另一个承诺?

Why isnt promise.then executed before the value was returned? How can I obtain a value from this promise instead of another promise?

推荐答案

如果你依赖于一个承诺,以恢复你的数据,你必须从你的函数返回一个承诺。

If you depend on a promise in order to return your data, you must return a promise from your function.

在1功能的调用堆栈是异步,希望所有的函数调用它必须是异步为好。 (异步=返回一个承诺)

Once 1 function in your callstack is async, all functions that want to call it have to be async as well. ( async = return a promise )

注意,之后如果条件不满足就不会执行你的如果语句没有括号,因此只有第一个声明。

Notice that your if statement does not have braces and thus only the first statement after it will not be executed if the condition fails.

我在这个例子中固定它。请注意,我说的话。

I fixed it in this example. Notice the remarks I added.

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;    
    });
}

您必须按以下方式调用 makeGeoCodingRequest

You must call makeGeoCodingRequest in the following fashion.

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