代码改变世界

异步调用框架Async.Operation

2009-05-07 11:44  Cat Chen  阅读(764)  评论(0编辑  收藏  举报
Async = {
    Operation: 
function() {
        
var callbackQueue = [];
        
this.result = undefined;
        
this.state = "running";
        
this.completed = false;

        
this.yield = function(result) {
            
var self = this;
            setTimeout(
function() {
                self.result 
= result;
                self.state 
= "completed";
                self.completed 
= true;

                
while (callbackQueue.length > 0{
                    
var callback = callbackQueue.shift();
                    callback(self.result);
                }

            }
1);
            
return this;
        }
;

        
this.addCallback = function(callback) {
            callbackQueue.push(callback);
            
if (this.completed) {
                
this.yield(this.result);
            }

            
return this;
        }
;
    }

}
;