@@ -209,14 +209,23 @@ export async function renderToAsyncIterable(
209
209
let error : Error | null = null ;
210
210
// The `next` is an object `{ promise, resolve, reject }` that we use to wait
211
211
// for chunks to be pushed into the buffer.
212
- let next = promiseWithResolvers < void > ( ) ;
212
+ let next : ReturnType < typeof promiseWithResolvers < void > > | null = null ;
213
213
const buffer : Uint8Array [ ] = [ ] ; // []Uint8Array
214
+ let renderingComplete = false ;
214
215
215
216
const iterator : AsyncIterator < Uint8Array > = {
216
217
async next ( ) {
217
218
if ( result . cancelled ) return { done : true , value : undefined } ;
218
219
219
- await next . promise ;
220
+ if ( next !== null ) {
221
+ await next . promise ;
222
+ }
223
+
224
+ // Only create a new promise if rendering is still ongoing. Otherwise
225
+ // there will be a dangling promises that breaks tests (probably not an actual app)
226
+ if ( ! renderingComplete ) {
227
+ next = promiseWithResolvers ( ) ;
228
+ }
220
229
221
230
// If an error occurs during rendering, throw the error as we cannot proceed.
222
231
if ( error ) {
@@ -276,8 +285,7 @@ export async function renderToAsyncIterable(
276
285
// Push the chunks into the buffer and resolve the promise so that next()
277
286
// will run.
278
287
buffer . push ( bytes ) ;
279
- next . resolve ( ) ;
280
- next = promiseWithResolvers < void > ( ) ;
288
+ next ?. resolve ( ) ;
281
289
}
282
290
} ,
283
291
} ;
@@ -286,12 +294,14 @@ export async function renderToAsyncIterable(
286
294
renderPromise
287
295
. then ( ( ) => {
288
296
// Once rendering is complete, calling resolve() allows the iterator to finish running.
289
- next . resolve ( ) ;
297
+ renderingComplete = true ;
298
+ next ?. resolve ( ) ;
290
299
} )
291
300
. catch ( ( err ) => {
292
301
// If an error occurs, save it in the scope so that we throw it when next() is called.
293
302
error = err ;
294
- next . resolve ( ) ;
303
+ renderingComplete = true ;
304
+ next ?. resolve ( ) ;
295
305
} ) ;
296
306
297
307
// This is the Iterator protocol, an object with a `Symbol.asyncIterator`
0 commit comments