所以我有一个这样的函数-
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
)我希望仅当所有请求都已返回时才返回coords。我该怎么做?
发布于 2013-08-19 11:05:52
下划线与_.after方法捆绑在一起。_.after有两个参数。第二个是您想要执行的函数,第一个是您希望它在执行之前被调用的次数。您可以通过以下方式使用它来完成您想要做的事情:
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
复制相似问题