Skip to content

Commit

Permalink
Replace setImmedaite with Promise.resolve().then(fn
Browse files Browse the repository at this point in the history
  • Loading branch information
MaxLeiter committed Aug 15, 2023
1 parent 696a93c commit 993c64b
Showing 1 changed file with 10 additions and 11 deletions.
21 changes: 10 additions & 11 deletions packages/next/src/server/stream-utils/node-web-streams-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import { getTracer } from '../lib/trace/tracer'
import { AppRenderSpan } from '../lib/trace/constants'
import { decodeText, encodeText } from './encode-decode'

const queueTask =
process.env.NEXT_RUNTIME === 'edge' ? globalThis.setTimeout : setImmediate
const queueTask: (fn: () => void) => void =
process.env.NEXT_RUNTIME === 'edge'
? (fn: () => void) => Promise.resolve().then(fn)
: setImmediate

export type ReactReadableStream = ReadableStream<Uint8Array> & {
allReady?: Promise<void> | undefined
Expand Down Expand Up @@ -107,12 +109,12 @@ export function createBufferedTransformStream(): TransformStream<
const flushBuffer = (controller: TransformStreamDefaultController) => {
if (!pendingFlush) {
pendingFlush = new Promise((resolve) => {
setTimeout(async () => {
queueTask(async () => {
controller.enqueue(bufferedBytes)
bufferedBytes = new Uint8Array()
pendingFlush = null
resolve()
}, 0)
})
})
}
return pendingFlush
Expand Down Expand Up @@ -230,7 +232,7 @@ function createDeferredSuffixStream(
// NOTE: streaming flush
// Enqueue suffix part before the major chunks are enqueued so that
// suffix won't be flushed too early to interrupt the data stream
setTimeout(() => {
queueTask(() => {
controller.enqueue(encodeText(suffix))
res()
})
Expand Down Expand Up @@ -265,13 +267,10 @@ export function createInlineDataStream(
// the safe timing to pipe the data stream, this extra tick is
// necessary.
dataStreamFinished = new Promise((res) =>
// We use `setTimeout` here to ensure that it's inserted after flushing
// We use `queueTask` here to ensure that it's inserted after flushing
// the shell. Note that this implementation might get stale if impl
// details of Fizz change in the future.
// Also we are not using `setImmediate` here because it's not available
// broadly in all runtimes, for example some edge workers might not
// have it.
setTimeout(async () => {
queueTask(async () => {
try {
while (true) {
const { done, value } = await dataStreamReader.read()
Expand All @@ -284,7 +283,7 @@ export function createInlineDataStream(
controller.error(err)
}
res()
}, 0)
})
)
}
},
Expand Down

0 comments on commit 993c64b

Please sign in to comment.