javascript - Getting around asynchronous ajax get -


so have function -

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

it's being called

if @model.get('data')?   if @model.get('func')?     @points = @model.get('func')(@model.get('data')) 

however, @points undefined. want @points coords when console.log coords run(which array of length). i'm using _.after because want build coords results of multipl async calls.

how coordinates in coords?

you've left out callback parameter ipgeocoding the other answer. you're supposed doing this:

ipgeocoding = (data, callback) ->   finish = _.after(data.length, callback)   #... 

and you'd use like:

ipgeocoding(data, (coords) ->   # whatever needs done `coords`   # in here. ) 

from fine manual:

after _.after(count, function)

creates version of function run after first being called count times. useful grouping asynchronous responses, want sure async calls have finished, before proceeding.

so finish call won't until $.ajax calls have returned , callback called final coords.

also note there's no guarantee order of coords match order of data. if need maintain order you'll need build object in coords instead of array , re-order things @ end. assuming datum simple scalar this:

coords = { } finish = _.after(data.length, (coords) ->   in_order = (coords[datum] datum in data)   callback(in_order) ) 

and in success handler you'd coords[datum] = pair instead of coords.push(pair).


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo