我似乎无法解决这个问题。
我使用 Maxmind GeoIP2 JavaScript API 和异步回调来返回纬度、经度和分割或区域。
<script type="text/javascript" src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js"></script>
<!--Html tags ... -->
<script type="text/javascript">
geoip2.city(
function (response) {
var latitude = "";
var longitude = "";
var region = "";
latitude = response.location.latitude;
longitude = response.location.longitude;
region = response.subdivisions[0].iso_code;
//Other operations.
},
function (error) {
try {
console.log(error);
}
catch (ex) {
alert(ex);
}
}
);
</script>
<!--Html tags ... -->
<script type="text/javascript">
$(document).ready(function () {
//Synchronous JavaScript against the DOM.
});
</script>
然后,这些值应该返回并写入 ASP.NET Web 表单更新面板中的 DOM,该更新面板会自动回发到服务器。然后,服务器在自定义数据库中进行查找,并将最近的 50 个左右位置作为指向 Google map 的点返回,该 map 通过传递 jQuery 文档就绪的匿名函数在回发时呈现。
当然,事实并非如此。一切都不是按顺序发生的。 (我没想到会这样,我只需要知道解决问题的正确方法。)
我想补充一些其他内容:
- 它在 Maxmind 从旧的同步更改之前就可以工作
JavaScript API 调用此异步回调 API。 - 这不是我的代码或方法。我继承了这种美丽。
最佳答案
您只需将同步内容嵌套在任何异步回调中即可。异步编程的关键是记住 JS 中的函数只是对象并且可以传递。
因此,您可以预先定义所有回调,然后将它们相互链接。下面是示例(我假设您的数据库查找
是同步的),所以很抱歉,如果没有完全有意义,但给出了如何执行异步位的想法。
将所有内容放入 $(document.ready)
中,而不是将其分成 2 个脚本:
$(document).ready(function () {
var weHaveFailed = function(){
// do sad things
};
var getLocation = function(successCallback, failureCallback){
geoip2.city(
function (response) {
// success!! Unpack the response
var latitude = response.location.latitude;
var longitude = response.location.longitude;
var region = response.subdivisions[0].iso_code;
// ... do other stuff
// then callback the passed in successCallback function with your coordinates
// and the function we want to execute when THAT is successful
successCallback(latitude, longitude, region, updateTheLocations);
},
function (error) {
// failure :(
console.log(error.message);
failureCallback();
}
);
var lookup = function(lat, long, reg, successCallback){
var locations = [];
// ...get the data from the database, is this sync?
// ...assign the response to our locations array
// ... and call the passed in successCallback with the locations array
successCallback(locations);
};
var updateTheLocations = function(locations){
// We pass in the locations from the lookup call
// do happy things, like synchronous JavaScript against the DOM
};
// start the ball rolling, passing in the function we want to run when geoip2 gets the data
getLocation(lookup, weHaveFailed);
});
关于javascript - 异步 JavaScript 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27864294/