什么是正确的方法来找出什么时候一系列的callback(从循环开除)全部执行?

我是Node.js的新手,并且很好奇规定的方法是在一个进程(重复)上运行一个循环,在执行结束时需要执行一些下一步操作,但是只有在所有迭代的callback之后被解雇。

具体来说,我正在进行SQL调用,我需要closuressql连接进行一堆插入和更新后,但由于它们都是asynchronous的,我无法知道什么时候所有的事实上都完成了,所以我可以在会话中调用end()。

显然这是一个远远超出这个特殊例子的问题,所以,我不是在寻找关于sql的具体解决scheme,而是更多的一般的做法,到目前为止,我有点被难住了。

我现在所做的实际上是设置一个全局计数器,以便在每个callback中循环对象的长度递减,看看它什么时候到达零,但是这真的感觉很奇怪,我希望它们更优雅(和以Javascript为中心)的方式来实现这种监控。

TIA

有一大堆stream控制库可以应用模式来帮助这种事情。 我最喜欢的是asynchronous 。 如果您想要依次运行一堆SQL查询,例如,您可以使用series

 async.series([ function(cb) { sql.exec("SOME SQL", cb) }, function(cb) { sql.exec("SOME MORE SQL", cb) }, function(cb) { sql.exec("SOME OTHER SQL", cb) } ], function(err, results) { // Here, one of two things are true: // (1) one of the async functions passed in an error to its callback // so async immediately calls this callback with a non-null "err" value // (2) all of the async code is done, and "results" is // an array of each of the results passed to the callbacks }); 

我写了自己的队列库来做这件事(我将这些日子之一发布),基本上推送查询到一个队列(基本上是一个数组)执行每个队列,因为它被删除,有一个callback发生时,数组是空的。

这并不需要太多的工作。

*编辑。 我已经添加了这个示例代码。 这不是我之前用过的,我没有在实践中尝试过,但它应该给你一个出发点。 这个模式还有很多可以做的。

有一件事要注意。 排队有效地使你的行为同步,他们一个接一个地发生。 我写了我的mysql队列脚本,这样我就可以在多个表上asynchronous地执行查询,但同时在任何一个表上执行查询,以便插入和select按请求的顺序发生。

 var queue = function() { this.queue = []; /** * Allows you to pass a callback to run, which is executed at the end * This example uses a pattern where errors are returned from the * functions added to the queue and then are passed to the callback * for handling. */ this.run = function(callback){ var i = 0; var errors = []; while (this.queue.length > 0) { errors[errors.length] = this.queue[i](); delete this.queue[i]; i++; } callback(errors); } this.addToQueue = function(callback){ this.queue[this.queue.length] = callback; } } 

使用:

 var q = new queue(); q.addToQueue(function(){ setTimeout(function(){alert('1');}, 100); }); q.addToQueue(function(){ setTimeout(function(){alert('2');}, 50); }); q.run();