Skip to content

Instantly share code, notes, and snippets.

@Schniz
Created September 2, 2014 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Schniz/0f525060aa9bec0b8d69 to your computer and use it in GitHub Desktop.
Save Schniz/0f525060aa9bec0b8d69 to your computer and use it in GitHub Desktop.
simple promises demonstration for Yoshi.
// 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.";
});
@Schniz
Copy link
Author

Schniz commented Sep 9, 2014

watch it over here: http://jsfiddle.net/rckaf6Lm/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment