所以目前正在开发一个可以完成相当多数据库工作的应用程序,并认为解决这个问题的一种聪明方法应该是使用事件。因此,我为应用程序设置了一个事件发射器,然后使用它作为控制流的方法。我有点假设事件发射器的工作方式与消息队列类似。
情况并非如此,由于某种原因,我不能让偶数发射器在第二次调用同一函数时按预期工作。
我会理解,如果问题是它多次调用,但实际上,下面的代码将运行第二个函数两次,但只会传递dbEvents.once('Ready'
一次。我不仅无法弄清楚为什么,它似乎不断地工作,并且永远不会打印出来"写第四个"
var mongo = require('mongodb');
var events = require('events');
var dbEvents = new events.EventEmitter();
function writeStuff(first, second, status, cuID){
console.log('Wrote '+ first);
if (status === 1) {
console.log('\t\tReady for '+ cuID);
dbEvents.emit('Ready');
} else {
console.log('\t\tReady (but not 1) for ' + cuID);
dbEvents.emit('Ready');
}
console.log('\t\tjust about to kick of number ' + status);
dbEvents.once('Ready', function (condata) {
console.log('Wrote '+ second)
dbEvents.emit('Done'+cuID)
});
}
var cuID1 = mongo.ObjectID();
writeStuff('First', 'Second', 1, cuID1);
dbEvents.on('Done'+cuID1, function(){
console.log('\tFirst completed ' + cuID1);
});
var cuID2 = mongo.ObjectID();
writeStuff('Third', 'Forth', 2, cuID2);
dbEvents.on('Done'+cuID2, function(){
console.log("\tSecond completed " + cuID2)
});
var b = 0;
for(var i = 0; i < 100000000; i++){
b++;
}
console.log("And I counted to " + b);
运行上述代码时的输出如下所示
Wrote First
Ready for 5540c57cd8fa9555076f9aba
just about to kick of number 1
Wrote Third
Ready (but not 1) for 5540c57cd8fa9555076f9abb
Wrote Second
First completed 5540c57cd8fa9555076f9aba
just about to kick of number 2
And I counted to 100000000
================更新==============
为什么我无法生成活动,I.E。如果我使用唯一标识符,我似乎不能将其作为事件发送。在这种情况下,我将事件更改为Ready + cuID(mongodb),现在第二次写入永远不会被调用。
var mongo = require('mongodb');
var events = require('events');
var dbEvents = new events.EventEmitter();
function writeStuff(first, second, status, cuID){
console.log('Wrote '+ first);
if (status === 1) {
console.log('\t\tReady for '+ cuID);
var flag = 'Ready'+cuID
dbEvents.emit(flag);
} else {
console.log('\t\tReady (but not 1) for ' + cuID);
dbEvents.emit('Ready');
}
console.log('\t\tjust about to kick of number ' + status);
dbEvents.once(flag, function (condata) {
console.log('Wrote '+ second)
dbEvents.emit('Done'+cuID)
});
}
var cuID1 = mongo.ObjectID();
writeStuff('First', 'Second', 1, cuID1);
dbEvents.on('Done'+cuID1, function(){
console.log('\tFirst completed ' + cuID1);
});
var cuID2 = mongo.ObjectID();
writeStuff('Third', 'Forth', 2, cuID2);
dbEvents.on('Done'+cuID2, function(){
console.log("\tSecond completed " + cuID2)
});
var b = 0;
for(var i = 0; i < 1000000000; i++){
b++;
}
console.log("And I counted to " + b);