Skip to content

Instantly share code, notes, and snippets.

@jdkanani
Created August 2, 2017 11:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdkanani/2dbf4b461e9f203dfd8a0d78c64f7a1a to your computer and use it in GitHub Desktop.
Save jdkanani/2dbf4b461e9f203dfd8a0d78c64f7a1a to your computer and use it in GitHub Desktop.
Javascript decorators
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