了解异步请求 [英] Getting around asynchronous requests

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

问题描述

所以我有一个这样的函数 -

So I have a function like this -

    IPGeocoding = (data) ->
    coords = []
    _.each(data, (datum) ->
        $.ajax(
          url: "http://freegeoip.net/json/#{datum}"
          type: 'GET'
          async: false
          success: (result) ->
            lat = result.latitude
            lon = result.longitude
            pair = [lat, lon]
            coords.push(pair)
            console.log coords
        )

    return coords


    )



我希望coords只在所有请求都返回时返回。我怎么做?

I want coords to only be returned when all of the requests have returned. How do I do that?

推荐答案

Underscore与 _ 方法捆绑在一起。 _。after 接受两个参数。第二个是要执行的函数,第一个是你希望它被执行之前调用的次数。它可以用以下方式完成你想要做的:

Underscore comes bundled with a _.after method. _.after takes two arguments. The second is the function you want to execute and the first is the number of times you expect it to be called BEFORE you want it executed. It can be used in the following manner to accomplish what you're attempting to do:

IPGeocoding = (data, callback) ->
    coords = []
    finish = _.after(data.length, callback)
    _.each(data, (datum) ->
        $.ajax(
            url: "http://freegeoip.net/json/#{datum}"
            type: 'GET'
            async: false
            success: (result) ->
                lat = result.latitude
                lon = result.longitude
                pair = [lat, lon]
                coords.push(pair)
                console.log coords

                finish(coords)
         )
    )

这篇关于了解异步请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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