Guest User

Untitled

a guest
May 7th, 2012
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. var when = function(funcs){
  2. if(!(this instanceof when)){
  3. return new when(arguments);
  4. }
  5. this.funcs = Array.prototype.slice.call(funcs);
  6. }
  7. when.prototype = {
  8. then: function(then){
  9. var i = 0,
  10. funcs = this.funcs,
  11. l = funcs.length,
  12. results = [],
  13. // Custom Object replaces func when pass is called
  14. complete = {},
  15. // insure all functions have successfully completed
  16. // before calling then function
  17. try_then = function(){
  18. var i=0;
  19. // insure all functions have run
  20. while(i<l){
  21. if(funcs[i++]!==complete)return;
  22. }
  23. then(results);
  24. // Prevent multiple calls to then
  25. then = function(){};
  26. }
  27. while(i<l)(function(i){
  28. var pass = function(result){
  29. results[i] = result
  30. funcs[i] = complete;
  31. try_then();
  32. }
  33. funcs[i](pass)
  34. })(i++);
  35. }
  36. }
  37.  
  38. when(
  39. function(pass){
  40. setTimeout(pass,3000);
  41. },
  42. function(pass){
  43. pass('2nd');
  44. }
  45. )
  46. .then(function(results){
  47. console.log(results);
  48. })
Advertisement
Add Comment
Please, Sign In to add comment