【发布时间】:2016-01-26 22:09:12
【问题描述】:
这是我正在使用的内容: getLocation('123 Foobar Ln');
function getLocation(location) {
console.log(location); // prints 123 Foobar Ln
getLocationData(location, function(gotLocation) {
console.log('hello?'); // this doesn't print
return gotLocation;
});
}
function getLocationData(location, callback) {
geocoder.geocode(location, function(err, res) {
if (res[0] != undefined) {
geoaddress = (res[0].formattedAddress);
addressmessage = 'Formatted Address: ' + geoaddress;
callback(addressmessage);
} else {
geocoder.geocode(cleanedAddress, function(err, res) {
addressmessage = 'null';
if (res[0] != undefined) {
geoaddress = (res[0].formattedAddress);
addressmessage = 'Formatted Address: ' + geoaddress;
callback(addressmessage);
} else {
addressmessage = 'Address could not be found: ' + location;
callback(addressmessage);
}
});
}
});
}
我很难让 getLocation 对来自 getLocationData 的回调执行任何操作。
当我运行以下命令时,我得到的唯一输出是:123 Foobar Ln
有人能指出我在这里做错了什么吗?
【问题讨论】:
-
你永远不会调用它。您只需将其设置为等于该字符串。
-
通过使用 `callback(addressmessage) 修复了这个问题,但它仍然没有返回任何内容 =/
-
首先
geocode方法是aysnc,所以你在它们完成之前调用你的回调。将其移动到每个回调函数的底部。此外,您没有使用错误参数。将来,如果存在错误,则在每个带有错误参数的函数下方打印错误以获取一些见解。if(err){console.log('geocode error', err);},if(err){console.log('geocode clean error', err);} -
还有一个语法错误:在倒数第二行,去掉
})。 -
我可能对那个语法错误有误。当我在另一个屏幕上修改它时,或者代码发生了变化。我已经编辑为现在这些大括号。但是您仍然没有检查错误。这将是您找出关键问题是否出现问题的最快方法。
标签: javascript node.js callback google-geocoder