diff --git a/src/core.ts b/src/core.ts index cafdc71..b66252f 100644 --- a/src/core.ts +++ b/src/core.ts @@ -29,20 +29,14 @@ unstable_replaceInternalFunction( }, ); -const callbackStack = [new Set<() => void>()]; -let callbackPromise: Promise | undefined; +const callbackStack: Set<() => void>[] = []; const registerCallback = (callback: () => void) => { - const callbacks = callbackStack[callbackStack.length - 1]!; - callbacks.add(callback); - if (!callbackPromise && callbackStack.length === 1) { - callbackPromise = Promise.resolve().then(() => { - callbackPromise = undefined; - for (const callback of callbacks) { - callback(); - } - callbacks.clear(); - }); + if (callbackStack.length) { + callbackStack[callbackStack.length - 1]!.add(callback); + } else { + // invoke immediately + callback(); } }; diff --git a/tests/01_watch.spec.ts b/tests/01_watch.spec.ts index 040c2be..ca46149 100644 --- a/tests/01_watch.spec.ts +++ b/tests/01_watch.spec.ts @@ -37,13 +37,10 @@ describe('watch', () => { }); expect(data).toEqual([0]); ++state.nested.count; - await new Promise((r) => setTimeout(r)); expect(data).toEqual([0, 1]); ++state.count; - await new Promise((r) => setTimeout(r)); expect(data).toEqual([0, 1]); ++state.nested.anotherCount; - await new Promise((r) => setTimeout(r)); expect(data).toEqual([0, 1]); unwatch(); }); @@ -59,16 +56,19 @@ describe('watch with batch', () => { expect(data).toEqual([0]); batch(() => { ++state.count; + ++state.count; }); - expect(data).toEqual([0, 1]); + expect(data).toEqual([0, 2]); batch(() => { ++state.count; + ++state.count; }); - expect(data).toEqual([0, 1, 2]); + expect(data).toEqual([0, 2, 4]); unwatch(); batch(() => { ++state.count; + ++state.count; }); - expect(data).toEqual([0, 1, 2]); + expect(data).toEqual([0, 2, 4]); }); });