ddea9b4578234d167decaf1d06198b45479ebf13f0d27c20a24696bacf7bc5c82c3d8dca23ab9b581e9cb513d8693b21fc0054893ef4c647c205c504437a2d 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * Copyright (c) 2019 ESHA Research
  3. * Dual licensed under the MIT and GPL licenses:
  4. * http://www.opensource.org/licenses/mit-license.php
  5. * http://www.gnu.org/licenses/gpl.html
  6. *
  7. * Adds an 'async' duplicate on all store APIs that
  8. * performs storage-related operations asynchronously and returns
  9. * a promise.
  10. *
  11. * Status: BETA - works great, but lacks justification for existence
  12. */
  13. ;(function(window, _) {
  14. var dontPromisify = ['async', 'area', 'namespace', 'isFake', 'toString'];
  15. _.promisify = function(api) {
  16. var async = api.async = _.Store(api._id, api._area, api._ns);
  17. async._async = true;
  18. Object.keys(api).forEach(function(name) {
  19. if (name.charAt(0) !== '_' && dontPromisify.indexOf(name) < 0) {
  20. var fn = api[name];
  21. if (typeof fn === "function") {
  22. async[name] = _.promiseFn(name, fn, api);
  23. }
  24. }
  25. });
  26. return async;
  27. };
  28. _.promiseFn = function(name, fn, self) {
  29. return function promised() {
  30. var args = arguments;
  31. return new Promise(function(resolve, reject) {
  32. setTimeout(function() {
  33. try {
  34. resolve(fn.apply(self, args));
  35. } catch (e) {
  36. reject(e);
  37. }
  38. }, 0);
  39. });
  40. };
  41. };
  42. // promisify existing apis
  43. for (var apiName in _.apis) {
  44. _.promisify(_.apis[apiName]);
  45. }
  46. // ensure future apis are promisified
  47. Object.defineProperty(_.storeAPI, 'async', {
  48. enumerable: true,
  49. configurable: true,
  50. get: function() {
  51. var async = _.promisify(this);
  52. // overwrite getter to avoid re-promisifying
  53. Object.defineProperty(this, 'async', {
  54. enumerable: true,
  55. value: async
  56. });
  57. return async;
  58. }
  59. });
  60. })(window, window.store._);