Last active
February 21, 2019 20:48
-
-
Save joewright/d8e3979f13749a8635da919b6eb5a6dc to your computer and use it in GitHub Desktop.
minimal promise example
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
// 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); | |
}); |
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
// 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