本文介绍了了解异步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个这样的函数 -
So I have a function like this -
IPGeocoding = (data) -> coords = [] _.each(data, (datum) -> $.ajax( url: "freegeoip/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: "freegeoip/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) ) )更多推荐
了解异步请求
发布评论