Advertisement
Guest User

Untitled

a guest
Feb 6th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.83 KB | None | 0 0
  1. function promiseBasedSave(inputData) {
  2. // FIRST: you need to setup some state.
  3. var state = 'pending';
  4. var callbacks = [];
  5. var errorCallbacks = [];
  6. var value; // this is what we will finally resolve
  7. var error; // if any
  8. var promise = {
  9. then: function(callback, errorCallback) {
  10. // you need to save the callback, the error callback
  11. // also, you need to call them if the promise is already resolved
  12. if(typeof callback === 'function') {
  13. callbacks.push(callback);
  14. }
  15. if(typeof errorCallback === 'function') {
  16. errorCallbacks.push(errorCallback);
  17. }
  18. // there's a chance that the promise is already resolved.
  19. in that case, schedule the callbacks for execution immediately.
  20. if(state === 'resolved' && typeof callback === 'function') {
  21. // pass the value to the callback.
  22. callback(value);
  23. }
  24. if(state === 'rejected' && typeof errorCallback === 'function') {
  25. errorCallback(error);
  26. }
  27. }
  28. };
  29.  
  30. // SECOND: do some action (computation, maybe something async
  31. // like fetching data from google etc
  32. // for example, I'll save the params to some async storage like
  33. // a database or localStorage
  34. // let's assume this storage works in a regular, callback way
  35. // it will return to us an error, if any, or a response when saving went
  36. // well
  37. storage.save(inputData, function(err, response) {
  38. if(err) {
  39. // when errors, we'll need to resolve our error callbacks
  40. state = 'rejected';
  41. errorCallbacks.forEach(function(errorCb) {
  42. // we would have to surround this with try/catch so that
  43. // we ensure that all callbacks get called
  44. try {
  45. errorCb(error);
  46. } catch(e) {
  47. // ignore
  48. }
  49. });
  50. } else {
  51. // the other is a success branch. Let's say we have a response
  52. // but our Library only returns an `id` field from the database.
  53. // we store it as our promise value.
  54. value = response && Page on Page on response.id;
  55. callbacks.forEach(function(callback) {
  56. // again, ensure that all callbacks get called
  57. try {
  58. callback(value)
  59. } catch(e) {
  60. // ignore
  61. }
  62. });
  63. }
  64. });
  65. // THIRD: return our promise.
  66. return promise;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement