如果您依赖承诺来返回数据,则必须从函数中返回承诺。
一旦调用堆栈中的1个函数异步,那么要继续线性执行,所有要调用它的函数也必须异步。(异步=返回承诺)
请注意,您的
if语句没有花括号,因此,如果条件失败,则仅不会执行后面的第一条语句。
我在此示例中对其进行了修复。请注意我添加的备注。
if(address){ promise=Q($.ajax({ type: "GET", url: "https://maps.googleapis.com/maps/api/geopre/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);});


