asyn foreach in jQuery

做~自己de王妃 提交于 2020-01-12 10:27:13

问题


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.

I've thought something like this :

$.each(sources, function(key, val) {
    JSON CALL OF EACH SOURCE
}

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.

How could I do the 'each' in async mode with jQuery ??


回答1:


Using deferred objects:

// 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        
    ...
});

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


来源:https://stackoverflow.com/questions/13059000/asyn-foreach-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!