Created
May 7, 2013 00:28
-
-
Save tony1223/5529412 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
//}); |
35 行那裡的 this 基本上我沒有特別定義他該是什麼,那邊我沒有任何假設,所以丟 global 進去, XD
簡言之 cb 裡面的 this 我 assume 不會有人去用。
Thanks~~:D
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
不知道是不是我理解錯了,請問35行是不是應該改成:
cb.apply(defers,items);