//! SPDX-FileCopyrightText: 2025 Chris Duncan <chris@codecow.com>
//! SPDX-License-Identifier: GPL-3.0-or-later
-const queue: { task: Function, resolve: Function, reject: Function }[] = []
-
-let isIdle: boolean = true
+let job: Promise<void> = Promise.resolve()
/**
- * Serially executes asynchronous functions.
+ * Serially executes sync and async functions.
*/
-export async function enqueue<T> (task: () => Promise<T>): Promise<T> {
+export function enqueue<T> (task: () => T | Promise<T>): Promise<T> {
if (typeof task !== 'function') throw new TypeError('task is not a function')
- return new Promise<T>((resolve, reject): void => {
- queue.push({ task, resolve, reject })
- if (isIdle) process()
- })
-}
-
-function process (): void {
- const next = queue.shift()
- if (next == null) {
- isIdle = true
- } else {
- const { task, resolve, reject } = next
- isIdle = !task
- task?.().then(resolve).catch(reject).finally(process)
- }
+ const result = job.then(() => task(), () => task())
+ job = result.then(() => void 0, () => void 0)
+ return result
}