Created
September 2, 2014 20:08
-
-
Save Schniz/0f525060aa9bec0b8d69 to your computer and use it in GitHub Desktop.
simple promises demonstration for Yoshi.
This file contains 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
// USAGE: | |
// flick(function(willBeNull, next) { next("hey"); }).then(....).then(...); | |
var PPromise = function(callback) { | |
this.thenCallback = function() {}; | |
this.next = function() {}; | |
this.data = null; | |
this.resolved = false; | |
this.nextPromise = null; | |
} | |
PPromise.prototype.getNextPromise = function() { | |
this.nextPromise = this.nextPromise || new PPromise(); | |
return this.nextPromise; | |
}; | |
/** | |
* callback(data, nextCall) | |
*/ | |
PPromise.prototype.then = function(callback) { | |
this.thenCallback = callback; | |
if (this.resolved) this.callThen(); | |
return this.getNextPromise(); | |
}; | |
PPromise.prototype.resolve = function(data) { | |
this.data = data; | |
this.resolved = true; | |
this.callThen(); | |
}; | |
PPromise.prototype.callThen = function() { | |
var nextPromise = this.getNextPromise(); | |
return this.thenCallback(this.data, nextPromise.resolve.bind(nextPromise)); | |
}; | |
// Nice method for makin it easier to work with it | |
var flick = function(callback) { | |
var promise = new PPromise(); | |
promise.resolve(null); | |
return promise.then(callback); | |
}; | |
// EXAMPLE | |
flick(function(data, next) { | |
document.body.innerHTML = "Yoshi,"; | |
setTimeout(function() { | |
next(" it worked after 2 seconds."); | |
}, 2000); | |
}).then(function(data, next) { | |
document.body.innerHTML += data; | |
setTimeout(next, 1000); | |
}).then(function(data) { | |
document.body.innerHTML += " aaaaaaaand finished."; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
watch it over here: http://jsfiddle.net/rckaf6Lm/