同步asynchronous创build的承诺

我正在做一个小的nodejs程序,并且有一些麻烦知道程序的所有asynchronous操作何时完成。

目前,该程序执行以下步骤:

1 /用一些参数产生一个进程。 这个过程将在其stdout上打印数据。

2 /听取进程标准输出“数据”事件,每次打印某些东西时,程序会调用一个函数(我们将称之为“进程”),使用这些数据。

3 /这个过程函数将最终将数据插入到mongo数据库并发送消息给amqp服务器。

3 /当没有更多数据时,由于与amqp和mongo数据库的连接仍然存在,所以程序空闲,所以我需要知道所有工作何时能够closures连接。

所以,我试图使用when.js来使用promise,但是我不能让它为我想要实现的目的而工作。

我让“process”函数返回一个promise,当mongodb insert和amqp消息发送完成后,这个promise就会被parsing。 在我的程序中,我正在创build一个数组,它将接收所有可以调用when.all()以了解何时全部parsing的承诺。

但是,因为当生成的进程将数据打印到它的stdoutstream时,我正在asynchronous创buildpromise,所以调用when.all()是由一个看起来立即解决的空数组构成的。

这里是一个代码示例,说明我实现了什么:

var when = require('when') , _ = require('lodash') , cp = require('child_process'); var promises = []; function process(data) { var deferred = when.defer(); setTimeout(function () { deferred.resolve(true); }, 3000); // Let's say we need 3 seconds to process and save data return deferred.promise; } var ls = cp.spawn('ls', ['-la', '/usr/bin']); ls.stdout.on('data', function (data) { console.log('Received data, creating a promise to notify when this data is processed.'); promises.push(process(data)); }); when.all(promises).then(function (values) { console.log('All promises are now resolved', values); }); 

正如你可能猜到的,这个程序的输出是:

 All promises are now resolved [] Received data, creating a promise to notify when this data is processed. Received data, creating a promise to notify when this data is processed. Received data, creating a promise to notify when this data is processed. Received data, creating a promise to notify when this data is processed. Received data, creating a promise to notify when this data is processed. Received data, creating a promise to notify when this data is processed. Received data, creating a promise to notify when this data is processed. Received data, creating a promise to notify when this data is processed. Received data, creating a promise to notify when this data is processed. 

有没有办法使这个代码示例打印控制台消息以预期的顺序(这是第一行打印最后)?

谢谢。

只有在所有的承诺完成之后,你才需要打电话。 在你的评论中你提到:

我想我无法知道什么时候这样做

这是不正确的。 您可以知道什么时候使用close事件完成所有事情:

 ls.on('close',function(){ when.all(promises).then(function (values) { console.log('All promises are now resolved', values); }); });