Getting around asynchronous requests

£可爱£侵袭症+ 提交于 2019-12-11 21:57:02

问题


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


    )

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


回答1:


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)
         )
    )


来源:https://stackoverflow.com/questions/18305825/getting-around-asynchronous-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!