Last active
October 25, 2023 09:10
-
-
Save aliakakis/6c8d59310350a60b0342d4b61fae3051 to your computer and use it in GitHub Desktop.
Event Queue
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
/* 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