From 2186a08fa5e5583de5928942b0c37574b1888ab2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B2=81=E6=A0=91=E4=BA=BA?= Date: Thu, 18 May 2023 22:00:43 +0100 Subject: [PATCH] fix: replace `setImmediate` with a cross environment compatible version --- src/util/ConcurrentQueue.ts | 4 +++- src/util/__tests__/ConcurrentQueue.test.ts | 5 +++-- src/util/nextTick.ts | 11 +++++++++++ 3 files changed, 17 insertions(+), 3 deletions(-) create mode 100644 src/util/nextTick.ts diff --git a/src/util/ConcurrentQueue.ts b/src/util/ConcurrentQueue.ts index 4ce7771..896043b 100644 --- a/src/util/ConcurrentQueue.ts +++ b/src/util/ConcurrentQueue.ts @@ -1,3 +1,5 @@ +import { nextTickAsync } from './nextTick'; + export abstract class ConcurrentQueue { protected items: [T, (result: R) => void, (error: unknown) => void][] = []; @@ -37,7 +39,7 @@ export abstract class ConcurrentQueue { } catch (error: unknown) { reject(error); } finally { - await new Promise((resolve) => setImmediate(resolve)); + await nextTickAsync(); } } } diff --git a/src/util/__tests__/ConcurrentQueue.test.ts b/src/util/__tests__/ConcurrentQueue.test.ts index 58cf6b3..67db525 100644 --- a/src/util/__tests__/ConcurrentQueue.test.ts +++ b/src/util/__tests__/ConcurrentQueue.test.ts @@ -1,4 +1,5 @@ import { ConcurrentQueue } from '../ConcurrentQueue'; +import { nextTickAsync } from '../nextTick'; class SimpleQueue extends ConcurrentQueue { handler(_item: T): Promise { @@ -40,7 +41,7 @@ test('should be able to process the queue within limit', async () => { // Wait till all fullfilled while (queuedResolver.length !== 5) { - await new Promise((resolve) => setImmediate(resolve)); + await nextTickAsync(); } // Now it should've queued everything. @@ -92,7 +93,7 @@ test('it should move on to the next item in the queue once failed', async () => // Wait till all fullfilled while (queuedResolver.length !== 4) { - await new Promise((resolve) => setImmediate(resolve)); + await nextTickAsync(); } // Should've moved on, as 3 will throw error diff --git a/src/util/nextTick.ts b/src/util/nextTick.ts new file mode 100644 index 0000000..59b1102 --- /dev/null +++ b/src/util/nextTick.ts @@ -0,0 +1,11 @@ +type NextTickFn = (callback: () => void) => void; +const nextTickFn = + typeof setImmediate !== 'undefined' + ? (setImmediate as NextTickFn) + : typeof requestAnimationFrame !== 'undefined' + ? (requestAnimationFrame as NextTickFn) + : (setTimeout as NextTickFn); + +export async function nextTickAsync() { + return new Promise((resolve) => nextTickFn(resolve)); +}