Skip to content

Instantly share code, notes, and snippets.

@tony1223
Created May 7, 2013 00:28
Show Gist options
  • Save tony1223/5529412 to your computer and use it in GitHub Desktop.
Save tony1223/5529412 to your computer and use it in GitHub Desktop.
function defer(){
return {
resolved:false,
resolved_arguments:null,
queue:[],
then:function(cb){
if(this.resolved){
cb.apply(this,this.resolved_arguments);
}else{
this.queue.push(cb);
}
},
resolve:function(){
this.resolved = true;
this.resolved_arguments = arguments;
for(var i = 0 ; i < this.queue.length ;++i){
this.queue[i].apply(this,this.resolved_arguments);
}
}
};
}
function when(defers,cb){
var index = 0 ;
var max = defers.length;
for(var i = 0; i < defers.length;++i){
defers[i].then(function(){
index ++;
if(index == max ){
var items = [];
for(var i = 0;i<defers.length;++i){
items.push(defers[i].resolved_arguments);
}
cb.apply(this,items);
}
});
}
}
//---test case1---
// var d = defer();
// d.then(function(){
// console.log(arguments);
// });
// setTimeout(function(){
// d.resolve("test","test2");
// },3000);
// d.then(function(){
// console.log(arguments);
// });
//---test case2---
//var d = defer();
//setTimeout(function(){
// d.resolve("test","test2");
//},3000);
//var e = defer();
//setTimeout(function(){
// e.resolve("testeee");
//},4000);
//when([d,e],function(){
// console.log(arguments);
//});
@kevin-shu
Copy link

不知道是不是我理解錯了,請問35行是不是應該改成:
cb.apply(defers,items);

@tony1223
Copy link
Author

tony1223 commented May 7, 2013

35 行那裡的 this 基本上我沒有特別定義他該是什麼,那邊我沒有任何假設,所以丟 global 進去, XD
簡言之 cb 裡面的 this 我 assume 不會有人去用。

@kevin-shu
Copy link

Thanks~~:D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment