javascript - 从 Promise 返回一个值

标签 javascript jquery ajax 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;    
        });
}

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

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

为什么promise.then没有在返回值之前执行?我怎样才能从这个 promise 而不是另一个 promise 中获得值(value)?

最佳答案

如果您依赖 promise 来返回数据,则必须从函数中返回 promise 。

一旦你的调用栈中的 1 个函数是异步的,如果你想继续线性执行,所有想要调用它的函数也必须是异步的。 (异步 = 返回 promise )

请注意,您的 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;    
    });
}

您必须按以下方式调用 makeGeoCodingRequest

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

关于javascript - 从 Promise 返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25530263/

相关文章:

javascript - jquery 相当于 javascript 间隔函数

c# - .NET 中 AJAX 和 ViewState 的行为不一致

javascript - Jquery - 数据从垂直格式到水平格式

javascript - 如何在 C# 或 WPF 中执行 javascript 函数

jquery - 带有固定横幅 div 的固定表头

jquery - 对 jQuery 有哪些常见的误解?

javascript - 网页中的可旋转 3D 模型

javascript - 获取 API 返回空字符串

javascript - 如何在jquery中动态初始化组件到输入字段

javascript - 使 Ajax 请求递归 - 检查文件是否存在