@@ -168,19 +168,8 @@ export function addTokenListener(
168
168
...state ,
169
169
tokenObservers : [ ...state . tokenObservers , tokenObserver ]
170
170
} ;
171
- /**
172
- * Invoke the listener with the valid token, then start the token refresher
173
- */
174
- if ( ! newState . tokenRefresher ) {
175
- const tokenRefresher = createTokenRefresher ( appCheck ) ;
176
- newState . tokenRefresher = tokenRefresher ;
177
- }
178
171
179
- // Create the refresher but don't start it if `isTokenAutoRefreshEnabled`
180
- // is not true.
181
- if ( ! newState . tokenRefresher . isRunning ( ) && state . isTokenAutoRefreshEnabled ) {
182
- newState . tokenRefresher . start ( ) ;
183
- }
172
+ let cacheCheckPromise = Promise . resolve ( ) ;
184
173
185
174
// Invoke the listener async immediately if there is a valid token
186
175
// in memory.
@@ -194,7 +183,7 @@ export function addTokenListener(
194
183
} else if ( state . token == null ) {
195
184
// Only check cache if there was no token. If the token was invalid,
196
185
// skip this and rely on exchange endpoint.
197
- void state
186
+ cacheCheckPromise = state
198
187
. cachedTokenPromise ! // Storage token promise. Always populated in `activate()`.
199
188
. then ( cachedToken => {
200
189
if ( cachedToken && isValid ( cachedToken ) ) {
@@ -206,6 +195,25 @@ export function addTokenListener(
206
195
} ) ;
207
196
}
208
197
198
+ // Wait for any cached token promise to resolve before starting the token
199
+ // refresher. The refresher checks to see if there is an existing token
200
+ // in state and calls the exchange endpoint if not. We should first let the
201
+ // IndexedDB check have a chance to populate state if it can.
202
+ void cacheCheckPromise . then ( ( ) => {
203
+ if ( ! newState . tokenRefresher ) {
204
+ const tokenRefresher = createTokenRefresher ( appCheck ) ;
205
+ newState . tokenRefresher = tokenRefresher ;
206
+ }
207
+ // Create the refresher but don't start it if `isTokenAutoRefreshEnabled`
208
+ // is not true.
209
+ if (
210
+ ! newState . tokenRefresher . isRunning ( ) &&
211
+ state . isTokenAutoRefreshEnabled
212
+ ) {
213
+ newState . tokenRefresher . start ( ) ;
214
+ }
215
+ } ) ;
216
+
209
217
setState ( app , newState ) ;
210
218
}
211
219
0 commit comments