jQuery中ASYN的foreach [英] asyn foreach in jQuery
本文介绍了jQuery中ASYN的foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要的是运行在异步模式下的code以获得更快的响应(多线程)。
What I want is to run a code in asynchronous mode to get a faster response (multi-thread).
我有一个源与进给和我想要的数组是从每一个获取数据。
I have an array like "sources" with feeds and what I want is to get data from each one.
我想是这样的:
$.each(sources, function(key, val) {
JSON CALL OF EACH SOURCE
}
,然后组所有的结果在一个数组中,并显示它们。问题是,我想,由于一些人的JSON调用在异步模式需要一定的时间。
and then group all the results in an array and show them. The problem is that I want the json calls in asynchronous mode due to some of them take some time.
我怎么能做到每个'在使用jQuery异步模式??
How could I do the 'each' in async mode with jQuery ??
推荐答案
使用延迟对象:
// get an array of jqXHR objects - the AJAX calls will
// run in parallel, subject to browser limits on the number
// of concurrent connections to each host
var defs = $.map(sources, function() {
return $.ajax({ url: this });
});
// when they're all done, invoke this callback
$.when.apply($, defs).done(function() {
// "arguments" array will contain the result of each AJAX call
...
});
要改变AJAX功能,这样只有数据
参数返回,您可以使用 .pipe()
To alter the AJAX function so that only the data
argument is returned, you can use .pipe()
:
var defs = $.map(sources, function() {
return $.ajax({ url: this }).pipe(function(data, text, jqxhr) {
return data; // filtered result
});
});
这篇关于jQuery中ASYN的foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文