Created
March 28, 2016 20:51
-
-
Save colwem/6088dd58fdbb7bae780f 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
#!/usr/bin/env node | |
'use strict'; | |
var promise = { | |
state: 'pending', | |
value: null, | |
dependencies: [], | |
then: function(expression) { | |
var result = createPromise(); | |
if( this.state === 'pending' ) { | |
var self = this; | |
debugge; | |
this.dependencies.push( function(value) { | |
expression(value).then(function(newValue) { | |
result.fulfil(newValue); | |
return createPromise(); | |
}); | |
}); | |
} | |
else { | |
expression(this.value).then(function(newValue) { | |
result.fulfil(newValue); | |
return createPromise(); | |
}) | |
} | |
return result; | |
}, | |
fulfil: function(value) { | |
if (this.state !== 'pending') { | |
throw new Error('Trying to fulfil an already fulfilled promise!'); | |
} | |
else { | |
this.state = 'fulfilled'; | |
this.value = value; | |
var dependencies = this.dependencies; | |
this.dependencies = []; | |
dependencies.forEach(function(expression) { | |
expression(value); | |
}); | |
} | |
} | |
}; | |
var squareAreaAbstraction = function(side) { | |
var result = createPromise(); | |
result.fulfil(side * side); | |
return result; | |
}; | |
var printAbstraction = function(squareArea) { | |
var result = createPromise(); | |
result.fulfil(console.log(squareArea)); | |
return result; | |
}; | |
var sidePromise = createPromise(); | |
var squareAreaPromise = sidePromise.then(squareAreaAbstraction); | |
sidePromise.fulfil(10); | |
// var printPromise = squareAreaPromise.then(printAbstraction); | |
function createPromise() { | |
return Object.create(promise); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment