]> git.codecow.com Git - libnemo.git/commitdiff
Greatly simplify serial queue.
authorChris Duncan <chris@zoso.dev>
Fri, 15 May 2026 21:57:34 +0000 (14:57 -0700)
committerChris Duncan <chris@zoso.dev>
Fri, 15 May 2026 21:57:34 +0000 (14:57 -0700)
src/lib/ledger/queue.ts

index 326775a6d2596b7eb0696a3e56c01fd9d49cee02..30560bfa7516deb34666a2641fe1f5791f87df37 100644 (file)
@@ -1,28 +1,14 @@
 //! 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
 }