praks5432
praks5432

Reputation: 7792

Getting around asynchronous requests

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?

Upvotes: 0

Views: 53

Answers (1)

THEtheChad
THEtheChad

Reputation: 2432

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

Upvotes: 2

Related Questions