多个异步回调 - 使用数组来完成时触发功能 [英] Multiple Asynchronous Callbacks - Using an array to fire function when complete

查看:110
本文介绍了多个异步回调 - 使用数组来完成时触发功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Node.js的,使多个异步调用我需要时,他们处理数据全部完成。我被他们筑巢,但是这真的是低效的,因为人们不会开始,直到previous完成。我想出了这一点,只是想知道如果有什么公然错的:

 变种F =功能(){},
    actualCallback =函数(){/ *做真正的东西* /},
    回调= [F,F,F,F,actualCallback]aync(函数(){
    callbacks.shift()();
});
aync(函数(){
    callbacks.shift()();
});
aync(函数(){
    callbacks.shift()();
});
aync(函数(){
    callbacks.shift()();
});
aync(函数(){
    callbacks.shift()();
});


解决方案

你能不能定义通过数组的工作方式的功能?

 函数asyncSequence(回调){
  功能doAsync(){
    异步(函数(){
      如果回报(callbacks.length!);
      回调[0]();
      回调= callbacks.slice(1);
      的setTimeout(doAsync,0);
    });
  }
  doAsync();
}

然后调用与您的回调函数数组。

现在,如果你想同时推出所有的异步回调,那么我没有看到摆在首位的问题;刚开始他们是必要的。如果你需要做一个排序的加盟在所有这些的结尾,然而,那么你就必须跟踪的常规状态:

 函数asyncSequenceConcurrent(回调,whenFinished){
  无功不全= callbacks.length;
  对于(VAR I = 0; I< callbacks.length ++我){
    异步((功能(我){
      返回功能(){
        回调[I]();
        incomplete--;
        如果(!不完全统计){
          whenFinished();
        }
      };
    })(一世));
  }
}

I'm using Node.js and making multiple Asynchronous calls that I need to handle data with when they all finish. I was nesting them, but this was really inefficient as one wouldn't start until the previous finished. I came up with this, and just wondering if there's anything blatantly wrong with it:

var f = function(){},
    actualCallback = function() { /* Do real stuff */ },
    callbacks = [f, f, f, f, actualCallback];

aync(function() {
    callbacks.shift()();
});
aync(function() {
    callbacks.shift()();
});
aync(function() {
    callbacks.shift()();
});
aync(function() {
    callbacks.shift()();
});
aync(function() {
    callbacks.shift()();
});

解决方案

Can't you define a function that works its way through the array?

function asyncSequence(callbacks) {
  function doAsync() {
    async(function() {
      if (!callbacks.length) return;
      callbacks[0]();
      callbacks = callbacks.slice(1);
      setTimeout(doAsync, 0);
    });
  }
  doAsync();
}

Then you call that with your array of callback functions.

Now, if you want to launch all the asynchronous callbacks concurrently, then I don't see the problem in the first place; just start them as necessary. If you need to do a sort of "join" at the end of all of them, however, then you'd have to keep track of the general status:

function asyncSequenceConcurrent(callbacks, whenFinished) {
  var incomplete = callbacks.length;
  for (var i = 0; i < callbacks.length; ++i) {
    async((function(i) {
      return function() {
        callbacks[i]();
        incomplete--;
        if (!incomplete) {
          whenFinished();
        }
      };
    })(i));
  }
}

这篇关于多个异步回调 - 使用数组来完成时触发功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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