Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement