异步JavaScript回调 [英] Async JavaScript Callback

查看:95
本文介绍了异步JavaScript回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法解决这个问题.

I can't seem to get my head around this problem.

我正在将Maxmind GeoIP2 JavaScript API与异步回调一起使用,以返回纬度,经度和细分或区域.

I'm using the Maxmind GeoIP2 JavaScript API with an async callback to return latitude, longitude and subdivision or region.

    <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的点,该Google Map通过将jQuery文档传递给anon函数传递而在回发时呈现.

Those values should then come back and are written to the DOM in an ASP.NET Web Forms Update Panel which does an auto postback to the server. The server then does a lookup in a custom database and returns the nearest 50 or so locations as points to a Google Map which is rendered on postback by passing jQuery document ready an anon function.

当然,这不会发生.一切都不是顺序发生的. (我不希望如此,我只需要知道解决此问题的正确方法即可.)

Of course, this isn't what happens. Everything does not occur sequentially. (I wouldn't expect it to, I just need to know the correct way to address the issue.)

我想添加一些其他内容:

I'd like to add a couple of other things:

  1. 它在Maxmind从旧的同步更改之前工作了
    JavaScript API会对此异步回调API进行调用.
  2. 这不是我的代码或方法.我继承了这种美丽.
  1. It worked prior to Maxmind changing from the old synchronous
    JavaScript API calls to this async callback API.
  2. This is not my code or approach. I've inherited this beauty.

推荐答案

您只需要将您的同步内容嵌套在任何异步回调中.异步编程的关键是要记住JS中的函数只是对象,可以被传递.

You just need to nest your synchronous stuff inside any async callback. The key to async programming is remembering that functions in JS are just objects and can be passed around.

因此,您可以预先定义所有回调,然后将它们彼此链接在一起.下面是一个示例(我假设您的数据库lookup是同步的),因此道歉如果不是很合理,但是给出了如何执行异步位的想法.

So you define all your callbacks upfront, then chain them into one another. The below is by way of example (I assumed your database lookup was synchronous) so apologies if doesn't make perfect sense, but gives an idea on how to do the async bit.

将所有内容放入$(document.ready)中,而不是将其拆分为2个脚本:

Put everything inside the $(document.ready) rather than splitting it up into 2 scripts:

$(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回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆