代码改变世界

异步调用框架Async.Operation

2009-05-07 11:44 by Cat Chen, ... 阅读, ... 评论, 收藏,  编辑
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;
        }
;
    }

}
;