From ab554b0470e73fd69ebca3d9a462d3dae56a0c9d Mon Sep 17 00:00:00 2001 From: Jixun Wu 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)); +}