Any better way to combine multiple callbacks?

你。 提交于 2019-12-01 19:03:13

Async JS to the rescue (for both client-side and server-side JavaScript)! Your code may look like this (after including async.js):

var datain = ['google','facebook','youtube','twitter'];

var calls = [];

$.each(datain, function(i, el) {
    calls.push( function(callback) {
        $.ajax({
            url : 'http://www.' + el +'.com',
            error : function(e) {
                callback(e);
            },
            success : function(r){
                callback(null, r);
            }
        });
    });
});

async.parallel(calls, function(err, result) {
   /* This function will be called when all calls finish the job! */
   /* err holds possible errors, while result is an array of all results */
});

By the way: async has some other really helpful functions.

By the way 2: note the use of $.each.

You can use the jQuery Deferred object for this purpose.

var def = $.when.apply(null, xhrs) with xhrs being an array containing the return values of your $.ajax() requests. Then you can register a callback def.done(function() { ... }); and use the arguments array-like object to access the responses of the various requests. to properly process them, remove your complete callback and add dataType: 'text' and use the following callback for done():

function() {
    var response = Array.prototype.join.call(arguments, '');
    // do something with response
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!