Skip to content

Instantly share code, notes, and snippets.

@aliakakis
Last active October 25, 2023 09:10
Show Gist options
  • Save aliakakis/6c8d59310350a60b0342d4b61fae3051 to your computer and use it in GitHub Desktop.
Save aliakakis/6c8d59310350a60b0342d4b61fae3051 to your computer and use it in GitHub Desktop.
Event Queue
/* Example
const q = EventQueue({}); You can also use the 'new' keyword
q.enQueue(async () => {
// [CODE HERE]
});
OR
q.enQueue([
async () => {
// [CODE HERE]
},
async () => {
// [CODE HERE]
}
]);
*/
export const EventQueue = ({ showLogs = false }) => {
const tasks = [];
async function enQueue(task) {
if (task instanceof Array) {
tasks.unshift(...task.reverse());
} else {
tasks.unshift(task);
}
while (tasks.length) {
if (showLogs) console.log("TASKS ARRAY:", tasks);
let currentTaskRunning = tasks.pop();
if (typeof currentTaskRunning !== "function") {
console.error(
`Did you forget to pass a function? Type is ${typeof currentTaskRunning} with value ${currentTaskRunning}`
);
} else {
try {
await new Promise((resolve) => {
setTimeout(async () => {
await currentTaskRunning();
resolve("TASK SUCCESS");
}, 0);
});
} catch (error) {
console.log("TASK ERROR:", error);
}
}
}
}
return {
enQueue,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment