diff --git a/README.md b/README.md index e686e05bc4..fd5a22c46b 100644 --- a/README.md +++ b/README.md @@ -502,6 +502,11 @@ ctx(async ($) => { // _$.cwd refers to /foo // but _$.cwd !== $.cwd }) + +const ref = $.bind(null) +await ctx(($) => { + ref === $ // true +}, ref) ``` ### `log()` diff --git a/src/experimental.ts b/src/experimental.ts index 70138a4f53..ccf15d5060 100644 --- a/src/experimental.ts +++ b/src/experimental.ts @@ -81,8 +81,8 @@ export function startSpinner(title = '') { )(setInterval(spin, 100)) } -export function ctx(cb: (_$: Zx) => R): R { - const _$ = Object.assign($.bind(null), getCtx()) +export function ctx(cb: (_$: Zx) => R, ref: Zx = $.bind(null)): R { + const _$ = Object.assign(ref, getCtx()) return runInCtx(_$, cb, _$) } diff --git a/test/experimental.test.js b/test/experimental.test.js index 0336945f69..06e3ba30e4 100644 --- a/test/experimental.test.js +++ b/test/experimental.test.js @@ -111,6 +111,14 @@ test('ctx() provides isolates running scopes', async () => { $.verbose = false }) +test('ctx accepts optional ref', async () => { + const ref = $.bind(null) + + await ctx(($) => { + assert.is(ref, $) + }, ref) +}) + test('bound ctx is attached to Promise', async () => { const kResourceStoreSymbol = Object.getOwnPropertySymbols( new Promise(() => {})