Skip to content

Instantly share code, notes, and snippets.

@joewright
Last active February 21, 2019 20:48
Show Gist options
  • Save joewright/d8e3979f13749a8635da919b6eb5a6dc to your computer and use it in GitHub Desktop.
Save joewright/d8e3979f13749a8635da919b6eb5a6dc to your computer and use it in GitHub Desktop.
minimal promise example
// bare minimum promise implementation
function promise() {
// the promise caller will pass these along in `then`
this.successFn = function() {};
this.errorFn = function() {};
}
promise.prototype.resolve = function(result) {
this.successFn(result);
};
promise.prototype.reject = function(error) {
this.errorFn(error);
};
promise.prototype.catch = function(error) {
this.errorFn(error);
};
promise.prototype.then = function(successHandler, errorHandler) {
this.successFn = successHandler;
this.errorFn = errorHandler;
};
// Example usage
// do async things with a promise
function myAsyncFnWithPromise() {
// get our object with about 6 extra functions
var deferredPromise = new promise();
doSomethingAsyncWithCallbacks(function(err, res) {
if (err) {
return deferred.reject(err);
}
deferredPromise.resolve(res);
});
return deferredPromise;
}
myAsyncFnWithPromise().then(function(result) {
console.log('wow isnt this great', result);
}, function(err) {
console.error(err);
});
// bare minimum plain callbacks implementation
// nothing, just write the dang function
// example usage
// do async things with a callback
function myAsyncFn(done) {
doSomethingAsyncWithCallbacks(function(err, res) {
done(err, res);
});
// or
// doSomethingAsyncWithCallbacks(done);
}
myAsyncFn(function(err, result) {
if (err) {
throw err;
}
console.log('wow isnt this great', result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment