-
-
Save robotlolita/3ce219e7e2b4067f5be3 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
'use strict'; | |
var promise = { | |
state: 'pending', | |
value: null, | |
dependencies: [], | |
then: function(expression) { | |
var result = createPromise(); | |
if( this.state === 'pending' ) { | |
var self = this; | |
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() { | |
var p = Object.create(promise); | |
p.value = null; | |
p.dependencies = []; | |
p.state = 'pending'; | |
return p; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment