Skip to content Skip to sidebar Skip to footer

Getting Around Asynchronous Requests

So I have a function like this - IPGeocoding = (data) -> coords = [] _.each(data, (datum) -> $.ajax( url: 'http://freegeoip.net/json/#{datum}'

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

Post a Comment for "Getting Around Asynchronous Requests"