Skip to content

Instantly share code, notes, and snippets.

@entrptaher
Created January 18, 2018 16:48
Show Gist options
  • Save entrptaher/6a73f22cb0438aee38934264fe05838e to your computer and use it in GitHub Desktop.
Save entrptaher/6a73f22cb0438aee38934264fe05838e to your computer and use it in GitHub Desktop.
const PQueue = require("p-queue");
const queue = new PQueue({ concurrency: 1 });
const timeouts = [];
const intervals = [];
function clearTimeouts() {
for (var i = 0; i < timeouts.length; i++) {
clearTimeout(timeouts[i]);
}
}
function interVals() {
for (var i = 0; i < intervals.length; i++) {
clearInterval(intervals[i]);
}
}
const functionList = {
delayed(data) {
return new Promise((resolve, reject) => {
timeouts.push(
setTimeout(() => {
if (data.called === 5) {
return reject(`Some Error on ${data.called}`);
}
resolve(data);
}, 10)
);
});
}
};
function qwrapper(fn) {
return function(...args) {
return queue.add(() => fn(...args)).catch(e => {
clearTimeouts();
console.error(e, `\nCleaning Up Queue, current size: ${queue.size}`);
queue.clear();
return 'Got error and Cleaned Up';
});
};
}
function limitObjectFunctions(obj) {
return Object.assign(
{},
...Object.keys(obj).map(k => ({ [k]: qwrapper(obj[k]) }))
);
}
const exportableFunctionList = limitObjectFunctions(functionList);
for (var i = 1; i <= 10; ++i) {
exportableFunctionList
.delayed({ called: i })
.then(data =>
console.log(data, `Queue size: ${queue.size}, Pending: ${queue.pending}`)
)
}
queue.onIdle().then(() => {
console.log("Queue is empty");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment