任何更好的方式来组合多个回调? [英] Any better way to combine multiple callbacks?

查看:117
本文介绍了任何更好的方式来组合多个回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为多个值调用异步函数(使用循环),并等待这些结果。现在我使用下面的代码:

I need to call an async function (with loop) for multiple values and wait for those results. Right now I'm using the following code:

(function(){
    var when_done = function(r){ alert("Completed. Sum of lengths is: [" + r + "]"); }; // call when ready

    var datain = ['google','facebook','youtube','twitter']; // the data to be parsed
    var response = {pending:0, fordone:false, data:0}; // control object, "data" holds summed response lengths
        response.cb = function(){ 
            // if there are pending requests, or the loop isn't ready yet do nothing
            if(response.pending||!response.fordone) return; 
            // otherwise alert.
            return when_done.call(null,response.data); 
        }

    for(var i=0; i<datain; i++)(function(i){
        response.pending++; // increment pending requests count
        $.ajax({url:'http://www.'+datain[i]+'.com', complete:function(r){
            response.data+= (r.responseText.length);
            response.pending--; // decrement pending requests count
            response.cb(); // call the callback
        }});
    }(i));

    response.fordone = true; // mark the loop as done
    response.cb(); // call the callback
}()); 

这不是很优雅,但它做的工作。
有什么更好的方法吗?

This isn't all very elegant but it does the job. Is there any better way to do it? Perhaps a wrapper?

推荐答案

Async JS 到救援(对于客户端和服务器端JavaScript)!您的代码可能看起来像这样(包括async.js后):

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

顺便说一句:async还有其他一些非常有用的函数。

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

顺便说一句2:注意使用 $。each

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

这篇关于任何更好的方式来组合多个回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆