为了完整性并且如上所述,使用外部对象来保持完成状态可以实现相同的结果,其中 A() 和 B() 检查另一个是否已完成,如果是,则调用 C()。如:
var results={};
function onComplete(){
if(results['A'] && results['B'] && !results['C']) {
C();
}
}
function A(){
// ...
results['A']=true;
onComplete();
}
function B(){
// ...
results['B']=true;
onComplete();
}
可以通过在 A() 和 B() 中添加“isComplete”标志来替换结果对象,如下所示:
function A(){
// ...
A.isComplete=true;
onComplete();
}
并修改 onComplete 以检查这个新标志:
function onComplete(){
if(A.isComplete && ...
}
或者,同样使用事件:
var util=require('util'),
events=require('events'),
EventEmitter=events.EventEmitter;
function F(){
EventEmitter.call(this); // init ancestor
}
util.inherits(F,EventEmitter); // assign ancestor
F.prototype.A=function(){
var self=this;
console.log('running A()');
setTimeout(function(){ // simulate long running code - 5 seconds
F.prototype.A.isComplete=true;
self.emit('complete','A');
},5000);
};
F.prototype.B=function(){
var self=this;
console.log('running B()');
setTimeout(function(){ // simulate long running code - 3 seconds
F.prototype.B.isComplete=true;
self.emit('complete','B');
},3000);
};
F.prototype.C=function(){
console.log('running C()');
};
var f=new F;
f.on('complete',function(which){ // onComplete handler
console.log(which+'() is complete');
if(F.prototype.A.isComplete && F.prototype.B.isComplete){
f.C();
}
});
// start it up
f.A();
f.B();
它在运行时会产生:
>node example.js
running A()
running B()
B() is complete
A() is complete
running C()
>