Skip to content

Instantly share code, notes, and snippets.

@josescasanova
Created February 7, 2016 01:14
Show Gist options
  • Save josescasanova/03716a492e7cd8cb3453 to your computer and use it in GitHub Desktop.
Save josescasanova/03716a492e7cd8cb3453 to your computer and use it in GitHub Desktop.
function promiseBasedSave(inputData) {
// FIRST: you need to setup some state.
var state = 'pending';
var callbacks = [];
var errorCallbacks = [];
var value; // this is what we will finally resolve
var error; // if any
var promise = {
then: function(callback, errorCallback) {
// you need to save the callback, the error callback
// also, you need to call them if the promise is already resolved
if(typeof callback === 'function') {
callbacks.push(callback);
}
if(typeof errorCallback === 'function') {
errorCallbacks.push(errorCallback);
}
// there's a chance that the promise is already resolved.
in that case, schedule the callbacks for execution immediately.
if(state === 'resolved' && typeof callback === 'function') {
// pass the value to the callback.
callback(value);
}
if(state === 'rejected' && typeof errorCallback === 'function') {
errorCallback(error);
}
}
};
// SECOND: do some action (computation, maybe something async
// like fetching data from google etc
// for example, I'll save the params to some async storage like
// a database or localStorage
// let's assume this storage works in a regular, callback way
// it will return to us an error, if any, or a response when saving went
// well
storage.save(inputData, function(err, response) {
if(err) {
// when errors, we'll need to resolve our error callbacks
state = 'rejected';
errorCallbacks.forEach(function(errorCb) {
// we would have to surround this with try/catch so that
// we ensure that all callbacks get called
try {
errorCb(error);
} catch(e) {
// ignore
}
});
} else {
// the other is a success branch. Let's say we have a response
// but our Library only returns an `id` field from the database.
// we store it as our promise value.
value = response && Page on Page on response.id;
callbacks.forEach(function(callback) {
// again, ensure that all callbacks get called
try {
callback(value)
} catch(e) {
// ignore
}
});
}
});
// THIRD: return our promise.
return promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment