了解异步请求

编程入门 行业动态 更新时间:2024-10-28 01:22:58
本文介绍了了解异步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我有一个这样的函数 -

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

更多推荐

了解异步请求

本文发布于:2023-11-11 17:44:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579130.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!