Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Forked from colwem/promises.js
Last active Mar 28, 2016
Embed
What would you like to do?
'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