Created
August 2, 2017 11:06
-
-
Save jdkanani/2dbf4b461e9f203dfd8a0d78c64f7a1a to your computer and use it in GitHub Desktop.
Javascript decorators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function sleepFor (timeInMilliSeconds = 1000) { | |
return new Promise((resolve, reject)=>{ | |
setTimeout(resolve, timeInMilliSeconds); | |
}); | |
} | |
export function waitFor (...names) { | |
return (target, prop, descriptor) => { | |
const fn = descriptor.value; | |
let newFn = function (...args) { | |
let promises = names.map((name) => { | |
if (!(this[name] instanceof Promise)) { | |
throw new Error(`Expecting this['${name}'] to be a Promise`); | |
} | |
return this[name]; | |
}); | |
return Promise.all(promises).then(() => { | |
return fn.apply(this, args); | |
}); | |
} | |
descriptor.value = newFn; | |
return descriptor; | |
}; | |
} | |
export function retry (retryInterval = 5000, n = 3) { | |
return (target, prop, descriptor) => { | |
const fn = descriptor.value; | |
let _retry = 0; | |
let newFn = async function (...args) { | |
while (_retry === 0 || _retry < n) { | |
try { | |
return await fn.apply(this, args); | |
} catch (e) { | |
_retry++; | |
await sleepFor(retryInterval); | |
} | |
} | |
} | |
descriptor.value = newFn; | |
return descriptor; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment