Unverified Commit 56c324fb authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Simplified ensure promise handling (#55562)

In JS, Promise's are used to help manage async tasks and control flows. When code calls methods on a promise like `.then()`, `.catch()`, or `.finally()` the results of the promise are forwarded to the callback as soon as they're resolved. This serves to make a change to the promise creation such that we do not await on the promise until we're within the try/finally block. This will ensure that the promise will always be added to the map before it's resolved or rejected and it's cleanup (removing it from the active promises) is also completed.

This additionally introduces a new `scheduleOnNextTick` method and polyfill for `Promise.withResolvers()`.

`scheduleOnNextTick` is based on the scheduling algorithm used by https://github.com/graphql/dataloader which utilizes a `Promise.resolve()` combined with `process.nextTick` in order to schedule an operation to occur after the promises have resolved (see [graphql/dataloader](https://github.com/graphql/dataloader/blob/d336bd15282664e0be4b4a657cb796f09bafbc6b/src/index.js#L213-L255))

The `Promise.withResolvers()` polyfill is an implementation of a soon-to-be-landed spec for inside-out promises. [Read the spec](https://tc39.es/proposal-promise-with-resolvers/)
parent 0fea4465
...@@ -1485,18 +1485,15 @@ export default class HotReloader implements NextJsHotReloaderInterface { ...@@ -1485,18 +1485,15 @@ export default class HotReloader implements NextJsHotReloaderInterface {
? this.clientError ? this.clientError
: this.serverError || this.clientError : this.serverError || this.clientError
if (error) { if (error) {
return Promise.reject(error) throw error
} }
const res = (await this.onDemandEntries?.ensurePage({
return this.onDemandEntries?.ensurePage({
page, page,
clientOnly, clientOnly,
appPaths, appPaths,
match, match,
isApp, isApp,
})) as any })
if (res && res.err) {
throw res.err
}
} }
} }
...@@ -5,3 +5,12 @@ export interface AppPageRouteDefinition ...@@ -5,3 +5,12 @@ export interface AppPageRouteDefinition
extends RouteDefinition<RouteKind.APP_PAGE> { extends RouteDefinition<RouteKind.APP_PAGE> {
readonly appPaths: ReadonlyArray<string> readonly appPaths: ReadonlyArray<string>
} }
/**
* Returns true if the given definition is an App Page route definition.
*/
export function isAppPageRouteDefinition(
definition: RouteDefinition
): definition is AppPageRouteDefinition {
return definition.kind === RouteKind.APP_PAGE
}
import type { RouteMatch } from './route-match' import type { RouteMatch } from './route-match'
import type { AppPageRouteDefinition } from '../route-definitions/app-page-route-definition' import type { AppPageRouteDefinition } from '../route-definitions/app-page-route-definition'
import { RouteKind } from '../route-kind'
export interface AppPageRouteMatch extends RouteMatch<AppPageRouteDefinition> {} export interface AppPageRouteMatch extends RouteMatch<AppPageRouteDefinition> {}
/**
* Checks if the given match is an App Page route match.
* @param match the match to check
* @returns true if the match is an App Page route match, false otherwise
*/
export function isAppPageRouteMatch(
match: RouteMatch
): match is AppPageRouteMatch {
return match.definition.kind === RouteKind.APP_PAGE
}
type ScheduledFn<T = void> = () => T | PromiseLike<T>
/**
* Schedules a function to be called on the next tick after the other promises
* have been resolved.
*/
export function scheduleOnNextTick<T = void>(cb: ScheduledFn<T>): void {
// We use Promise.resolve().then() here so that the operation is scheduled at
// the end of the promise job queue, we then add it to the next process tick
// to ensure it's evaluated afterwards.
//
// This was inspired by the implementation of the DataLoader interface: https://github.com/graphql/dataloader/blob/d336bd15282664e0be4b4a657cb796f09bafbc6b/src/index.js#L213-L255
//
Promise.resolve().then(() => {
process.nextTick(cb)
})
}
...@@ -14,3 +14,31 @@ if (typeof (globalThis as any).WebSocket !== 'function') { ...@@ -14,3 +14,31 @@ if (typeof (globalThis as any).WebSocket !== 'function') {
}, },
}) })
} }
// This adds a `Promise.withResolvers` polyfill. This will soon be adopted into
// the spec.
//
// TODO: remove this polyfill when it is adopted into the spec.
//
// https://tc39.es/proposal-promise-with-resolvers/
//
if (
!('withResolvers' in Promise) ||
typeof Promise.withResolvers !== 'function'
) {
Promise.withResolvers = <T>() => {
let resolvers: {
resolve: (value: T | PromiseLike<T>) => void
reject: (reason: any) => void
}
// Create the promise and assign the resolvers to the object.
const promise = new Promise<T>((resolve, reject) => {
resolvers = { resolve, reject }
})
// We know that resolvers is defined because the Promise constructor runs
// synchronously.
return { promise, resolve: resolvers!.resolve, reject: resolvers!.reject }
}
}
...@@ -318,6 +318,21 @@ declare global { ...@@ -318,6 +318,21 @@ declare global {
randomUUID(): string randomUUID(): string
} }
// TODO: remove this polyfill when it is adopted into the spec.
interface PromiseConstructor {
/**
* Creates a new promise with exposed resolvers to resolve/reject. This will
* be adopted into the spec as `Promise.withResolvers`.
*
* @see https://tc39.es/proposal-promise-with-resolvers/
*/
withResolvers<T>(): {
promise: Promise<T>
resolve: (value: T | PromiseLike<T>) => void
reject: (reason?: unknown) => void
}
}
var __NEXT_HTTP_AGENT_OPTIONS: { keepAlive?: boolean } | undefined var __NEXT_HTTP_AGENT_OPTIONS: { keepAlive?: boolean } | undefined
var __NEXT_UNDICI_AGENT_SET: boolean var __NEXT_UNDICI_AGENT_SET: boolean
var __NEXT_HTTP_AGENT: HttpAgent var __NEXT_HTTP_AGENT: HttpAgent
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment