Skip to content

Instantly share code, notes, and snippets.

@relay-zz
relay-zz / deferred-min.js
Created September 8, 2012 06:29
Deferred (Twisted API) implementation with no dependencies
/*Copyright(c)2012 relay.github.com http://opensource.org/licenses/MIT*/function Deferred(){this.callbacks=[]} Deferred.prototype={err:0,x:0,$:function(a){this.callbacks.push(a);2==this.x&&this._(this.o);return this},done:function(a){return this.$([a,0])},fail:function(a){return this.$([0,a])},always:function(a){return this.$([0,0,a])},then:function(a,c){return this.$([a,c])},reject:function(a){this.x||(this.err=1,this._(a));return this},resolve:function(a){this.x||this._(a);return this},_:function(a){this.x=1;for(var c=this.err,d=this.callbacks,b=d.shift(),e=a;b;)try{for(;b;){(b=b[2]||(c?b[1]:b[0]))&&(e= b(e||a));if(e instanceof Deferred){var f=this;e.always(function(b){f._(b||a);return b});return}b=d.shift()}}catch(g){c&&(b=d.shift()),this.err=c=1}this.o=e||a;this.x=2}};Deferred.when=function(a,c){if(!c)return a;for(var c=[].slice.call(arguments),a=new Deferred,d=c.length,b=d,e=[],f=function(c){return function(d){e[c]=d;--b||a.resolve(e)}},g=function(b){a.reject(b)};d--;)c[d].then(f(d),g);return a};