export type Queue = ReturnType export const makeQueue = () => { const state = { queue: <(() => Promise)[]>[], workload: 0, } const process = async () => { const task = state.queue.shift() if (!task) return await task() state.workload-- await process() } return { enqueue: (callback: () => void | Promise): Promise => { return new Promise((resolve, reject) => { const task = async () => { try { await callback() resolve() } catch (error) { reject(error) } } state.queue.push(task) state.workload++ // If the queue has other items in it, then it will drain itself. if (state.workload > 1) return process() }) }, } }