@@ -54,11 +54,13 @@ const use =
54
54
}
55
55
} )
56
56
57
+ type ContinuablePromiseCache = WeakMap < PromiseLike < unknown > , Promise < unknown > >
58
+
57
59
type StoreHelpers = readonly [
58
60
changedHook : { add ( atom : Atom < unknown > , callback : ( ) => void ) : ( ) => void } ,
59
61
promiseCache : {
60
- get ( promise : PromiseLike < unknown > ) : Promise < unknown > | undefined
61
- set ( promise : PromiseLike < unknown > , value : Promise < unknown > ) : void
62
+ get ( atom : Atom < unknown > ) : ContinuablePromiseCache | undefined
63
+ set ( atom : Atom < unknown > , value : ContinuablePromiseCache ) : void
62
64
} ,
63
65
]
64
66
@@ -70,7 +72,7 @@ const getStoreHelpers = (store: Store) => {
70
72
const buildingBlocks = getBuildingBlocks ( store )
71
73
const storeHooks = initializeStoreHooks ( buildingBlocks [ 6 ] )
72
74
const changedHook = storeHooks . c
73
- const promiseCache = new Map < PromiseLike < unknown > , Promise < unknown > > ( )
75
+ const promiseCache = new WeakMap < Atom < unknown > , ContinuablePromiseCache > ( )
74
76
helpers = [ changedHook , promiseCache ]
75
77
StoreHelpersMap . set ( store , helpers )
76
78
}
@@ -83,17 +85,30 @@ const createContinuablePromise = <T>(
83
85
promise : PromiseLike < T > ,
84
86
) => {
85
87
const [ changedHook , promiseCache ] = getStoreHelpers ( store )
86
- let continuablePromise = promiseCache . get ( promise )
88
+ let continuablePromiseCache = promiseCache . get ( atom )
89
+ if ( ! continuablePromiseCache ) {
90
+ continuablePromiseCache = new WeakMap ( )
91
+ promiseCache . set ( atom , continuablePromiseCache )
92
+ }
93
+ let continuablePromise = continuablePromiseCache . get ( promise )
87
94
if ( ! continuablePromise ) {
88
95
continuablePromise = new Promise < T > ( ( resolve , reject ) => {
89
- let curr = promise
96
+ let curr : PromiseLike < T > | undefined = promise
90
97
const cleanup = changedHook . add ( atom , ( ) => {
91
- const nextValue = store . get ( atom )
92
- if ( isPromiseLike ( nextValue ) ) {
93
- curr = nextValue
94
- nextValue . then ( onFulfilled ( nextValue ) , onRejected ( nextValue ) )
95
- } else {
96
- resolve ( nextValue as T )
98
+ try {
99
+ const nextValue = store . get ( atom )
100
+ if ( isPromiseLike ( nextValue ) ) {
101
+ curr = nextValue
102
+ nextValue . then ( onFulfilled ( nextValue ) , onRejected ( nextValue ) )
103
+ } else {
104
+ curr = undefined
105
+ resolve ( nextValue as T )
106
+ cleanup ( )
107
+ }
108
+ } catch ( e ) {
109
+ curr = undefined
110
+ reject ( e )
111
+ cleanup ( )
97
112
}
98
113
} )
99
114
const onFulfilled = ( me : PromiseLike < T > ) => ( v : T ) => {
@@ -110,7 +125,7 @@ const createContinuablePromise = <T>(
110
125
}
111
126
promise . then ( onFulfilled ( promise ) , onRejected ( promise ) )
112
127
} )
113
- promiseCache . set ( promise , continuablePromise )
128
+ continuablePromiseCache . set ( promise , continuablePromise )
114
129
}
115
130
return continuablePromise
116
131
}
0 commit comments