GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix: consume the promise returned by a thenable's then call (#743) · tinylibs/tinybench@15a2408

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • src
    • async.ts
    • task.ts
    • utils.ts
  • test
    • run-sync-hook-rejection.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎src/async.ts‎

Copy file name to clipboardExpand all lines: src/async.ts
+20-5Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,25 @@ export const isPromiseLike = <T>(
1515
typeof maybePromiseLike === 'function') &&
1616
typeof (maybePromiseLike as PromiseLike<T>).then === 'function'
1717

18+
/**
19+
* Suppresses rejections of a promise-like value, and of the promise its own
20+
* `then` call returns, so neither surfaces as an unhandled rejection.
21+
* @param value - the promise-like value to mark handled
22+
*/
23+
export const markHandled = (value: unknown): void => {
24+
try {
25+
const returned = (value as PromiseLike<unknown>).then(
26+
emptyFunction,
27+
emptyFunction
28+
)
29+
if (isPromiseLike(returned)) {
30+
Promise.resolve(returned).catch(emptyFunction)
31+
}
32+
} catch {
33+
// Treat a throwing `then` as handled
34+
}
35+
}
36+
1837
type AsyncFunctionType<A extends unknown[], R> = (...args: A) => PromiseLike<R>
1938

2039
const AsyncFunctionConstructor = (async () => {
@@ -48,11 +67,7 @@ export const isFnAsyncResource = (fn: Fn | null | undefined): boolean => {
4867
const promiseLike = isPromiseLike(fnCall)
4968
if (promiseLike) {
5069
// silence promise rejection
51-
try {
52-
(fnCall.then(emptyFunction) as Promise<unknown>).catch(emptyFunction)
53-
} catch {
54-
// ignore
55-
}
70+
markHandled(fnCall)
5671
}
5772
return promiseLike
5873
} catch {
Collapse file

‎src/task.ts‎

Copy file name to clipboardExpand all lines: src/task.ts
+14-8Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ import type {
1818
TimestampValue,
1919
} from './types'
2020

21-
import { emptyFunction } from './constants'
2221
import { BenchEvent } from './event'
2322
import {
2423
assert,
@@ -28,6 +27,7 @@ import {
2827
isFnAsyncResource,
2928
isPromiseLike,
3029
isValidSamples,
30+
markHandled,
3131
medianAbsoluteDeviation,
3232
sortSamples,
3333
toError,
@@ -50,7 +50,7 @@ const hookNames = ['afterAll', 'beforeAll', 'beforeEach', 'afterEach'] as const
5050
const assertSyncResult = (result: unknown, message: string): void => {
5151
const isAsync = isPromiseLike(result)
5252
if (isAsync) {
53-
Promise.resolve(result).catch(emptyFunction)
53+
markHandled(result)
5454
}
5555
assert(!isAsync, message)
5656
}
@@ -785,6 +785,14 @@ export class Task extends EventTarget {
785785
}
786786
}
787787

788+
/**
789+
* Whether a value is a finite, non-negative duration in milliseconds.
790+
* @param value - the value to check
791+
* @returns whether the value can be used as an overridden duration or cost
792+
*/
793+
const isValidDuration = (value: unknown): value is number =>
794+
typeof value === 'number' && Number.isFinite(value) && value >= 0
795+
788796
/**
789797
* Extracts a finite, non-negative `overriddenDuration`, otherwise undefined.
790798
* Checks own and inherited properties, reads the value once and propagates
@@ -806,14 +814,14 @@ function getOverriddenDurationFromFnResult (
806814
if (typeof value !== 'number') {
807815
try {
808816
if (isPromiseLike(value)) {
809-
Promise.resolve(value).catch(emptyFunction)
817+
markHandled(value)
810818
}
811819
} catch {
812820
// Treat access errors as absence
813821
}
814822
return undefined
815823
}
816-
return Number.isFinite(value) && value >= 0 ? value : undefined
824+
return isValidDuration(value) ? value : undefined
817825
}
818826

819827
/**
@@ -837,11 +845,9 @@ function getOverriddenIterationCostFromFnResult (
837845
}
838846
const value = record.overriddenIterationCost
839847
if (typeof value !== 'number' && isPromiseLike(value)) {
840-
Promise.resolve(value).catch(emptyFunction)
848+
markHandled(value)
841849
}
842-
return typeof value === 'number' && Number.isFinite(value) && value >= 0
843-
? value
844-
: undefined
850+
return isValidDuration(value) ? value : undefined
845851
} catch {
846852
return undefined
847853
}
Collapse file

‎src/utils.ts‎

Copy file name to clipboardExpand all lines: src/utils.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
export { isFnAsyncResource, isPromiseLike } from './async'
1+
export { isFnAsyncResource, isPromiseLike, markHandled } from './async'
22
export { withConcurrency } from './concurrency'
33
export { defaultConvertTaskResultForConsoleTable } from './console-table'
44
export { mToMs, mToNs, mToNsBigint, nToMs } from './conversions'
Collapse file

‎test/run-sync-hook-rejection.test.ts‎

Copy file name to clipboardExpand all lines: test/run-sync-hook-rejection.test.ts
+28Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,3 +124,31 @@ test.each([
124124
)
125125
}
126126
)
127+
128+
test('a task returning a thenable whose `then` call rejects leaks no unhandled rejection', async () => {
129+
const thenable = {
130+
then (resolve: (value?: unknown) => void): Promise<void> {
131+
resolve(undefined)
132+
return Promise.reject(new Error('late'))
133+
},
134+
}
135+
const bench = new Bench({ warmup: false })
136+
bench.add(
137+
'task',
138+
() => thenable,
139+
{ async: false }
140+
)
141+
142+
const { reasons, stop } = listenToUnhandledRejections()
143+
await bench.run()
144+
await flushTurns(3)
145+
stop()
146+
147+
expect(reasons).toEqual([])
148+
expect(bench.getTask('task')?.result).toMatchObject({
149+
error: {
150+
message: 'task function must be sync when using `runSync()`',
151+
},
152+
state: 'errored',
153+
})
154+
})

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.