From 2fbac34fe9bc479c16ee9537a3cae67aeac61c05 Mon Sep 17 00:00:00 2001 From: AdamW Date: Fri, 1 Nov 2024 15:36:43 +0200 Subject: [PATCH] fix(utils): make 'unwrap' update immediate after resolve --- src/vanilla/utils/unwrap.ts | 16 ++++++++++------ tests/vanilla/utils/unwrap.test.ts | 12 ++++++++++++ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/vanilla/utils/unwrap.ts b/src/vanilla/utils/unwrap.ts index 3313980171..2504f68d51 100644 --- a/src/vanilla/utils/unwrap.ts +++ b/src/vanilla/utils/unwrap.ts @@ -60,12 +60,16 @@ export function unwrap( return { v: promise as Awaited } } if (promise !== prev?.p) { - promise - .then( - (v) => promiseResultCache.set(promise, v as Awaited), - (e) => promiseErrorCache.set(promise, e), - ) - .finally(setSelf) + promise.then( + (v) => { + promiseResultCache.set(promise, v as Awaited) + setSelf() + }, + (e) => { + promiseErrorCache.set(promise, e) + setSelf() + }, + ) } if (promiseErrorCache.has(promise)) { throw promiseErrorCache.get(promise) diff --git a/tests/vanilla/utils/unwrap.test.ts b/tests/vanilla/utils/unwrap.test.ts index a0ca0ed8f5..be294dde54 100644 --- a/tests/vanilla/utils/unwrap.test.ts +++ b/tests/vanilla/utils/unwrap.test.ts @@ -137,4 +137,16 @@ describe('unwrap', () => { await new Promise((r) => setTimeout(r)) // wait for a tick expect(store.get(unwrap(asyncAtom))).toEqual('concrete') }) + + it('should get a fulfilled value after the promise resolves', async () => { + const store = createStore() + const asyncAtom = atom(Promise.resolve('concrete')) + const syncAtom = unwrap(asyncAtom) + + expect(store.get(syncAtom)).toEqual(undefined) + + await store.get(asyncAtom) + + expect(store.get(syncAtom)).toEqual('concrete') + }) })