daily pastebin goal
4%
SHARE
TWEET

Untitled

a guest Feb 18th, 2019 51 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { EventEmitter } from 'events';
  2.  
  3. export const bus = new EventEmitter();
  4.  
  5. function Deferred() {
  6.   const result = {};
  7.  
  8.   result.promise = new Promise((resolve, reject) => {
  9.     result.resolve = resolve;
  10.     result.reject = reject;
  11.   });
  12.  
  13.   return result;
  14. }
  15.  
  16. export default function once(resetKey, callback) {
  17.   let defer = null,
  18.     result = null;
  19.  
  20.   const doAction = () => {
  21.     defer = Deferred();
  22.     result = defer.promise.then(callback);
  23.  
  24.     const errorHandler = () =>
  25.       result.catch(e => {
  26.         defer = Deferred();
  27.         result = defer.promise.then(callback);
  28.  
  29.         errorHandler();
  30.  
  31.         throw e;
  32.       });
  33.     errorHandler();
  34.   };
  35.  
  36.   doAction();
  37.   if (resetKey) {
  38.     bus.on(resetKey, doAction);
  39.   }
  40.  
  41.   return function(...args) {
  42.     defer.resolve(...args);
  43.  
  44.     return result;
  45.   };
  46. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top