Last active
December 12, 2015 09:19
-
-
Save MaxMotovilov/4750596 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 Def( arg ) { | |
if( arg instanceof Def ) | |
this.parent = arg; | |
else if( typeof arg !== "undefined" ) | |
this.v = arg; | |
} | |
Def.prototype = { | |
chain: function(v){ | |
this.v = v; | |
}, | |
resolve: function( v ) { | |
if( v instanceof Def ) | |
v.then( this.resolve.bind( this ) ); | |
else if( this.cb ) | |
this.chain( this.cb( v ) ); | |
else | |
this.chain( v ); | |
}, | |
then: function( cb ) { | |
if( 'v' in this ) | |
return new Def( cb( this.v ) ); | |
if( this.parent ) | |
this.parent.chain = this.resolve.bind( this ); | |
this.cb = cb; | |
return new Def( this ); | |
} | |
} | |
console.log( "Test 1 - starting" ); | |
var a = new Def(); | |
a.then( function(v){ console.log( "Callback:", v ); } ) | |
console.log( "Test 1 - resolving" ); | |
a.resolve( "Value" ); | |
console.log( "Test 2 - starting" ); | |
var a = new Def(); | |
console.log( "Test 2 - resolving" ); | |
a.resolve( "Value" ); | |
a.then( function(v){ console.log( "Callback:", v ); } ) | |
console.log( "Test 3 - starting" ); | |
var a = new Def(); | |
a.then( function(v){ console.log( "Callback 1:", v ); return v; } ) | |
.then( function(v){ console.log( "Callback 2:", v ); } ); | |
console.log( "Test 3 - resolving" ); | |
a.resolve( "Value" ); | |
console.log( "Test 4 - starting" ); | |
var a = new Def(); | |
console.log( "Test 4 - resolving" ); | |
a.resolve( "Value" ); | |
a.then( function(v){ console.log( "Callback 1:", v ); return v; } ) | |
.then( function(v){ console.log( "Callback 2:", v ); } ); | |
console.log( "Test 5 - starting" ); | |
var a = new Def(); | |
var b = new Def(); | |
a.then( function(v){ console.log( "Callback:", v ); } ) | |
console.log( "Test 5 - resolving a" ); | |
a.resolve( b ); | |
console.log( "Test 5 - resolving b" ); | |
b.resolve( "Value" ); | |
console.log( "Test 6 - starting" ); | |
var a = new Def(); | |
var b = new Def(); | |
a.then( function(v){ console.log( "Callback 1:", v ); return b; } ) | |
.then( function(v){ console.log( "Callback 2:", v ); } ); | |
console.log( "Test 6 - resolving a" ); | |
a.resolve( "Value 1" ); | |
console.log( "Test 6 - resolving b" ); | |
b.resolve( "Value 2" ); | |
console.log( "Test 7 - starting" ); | |
var a = new Def(); | |
var b = new Def(); | |
a.then( function(v){ console.log( "Callback 1:", v ); return b; } ) | |
.then( function(v){ console.log( "Callback 2:", v ); } ); | |
console.log( "Test 7 - resolving b" ); | |
b.resolve( "Value 2" ); | |
console.log( "Test 7 - resolving a" ); | |
a.resolve( "Value 1" ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment