Skip to content

Commit 12eed81

Browse files
committed
feat: add getIsAsync helper
1 parent a0d4a2d commit 12eed81

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,23 @@ const result = myFunction.sync('./some-file.js')
5151
const asyncResult = await myFunction.async('./some-file.js')
5252
```
5353

54+
### `getIsAsync`
55+
56+
Returns a boolean indicating whether the current execution is in async mode.
57+
58+
```ts
59+
import { getIsAsync, quansync } from 'quansync'
60+
61+
const fn = quansync(function* () {
62+
const isAsync: boolean = yield* getIsAsync()
63+
console.log(isAsync)
64+
})
65+
66+
fn.sync() // false
67+
await fn() // true
68+
await fn.async() // true
69+
```
70+
5471
## Build-time Macro
5572

5673
If you don't like the `function*` and `yield*` syntax, we also provide a build-time macro via [unplugin-quansync](https://github.com/unplugin/unplugin-quansync#usage) allowing you use quansync with async/await syntax, while still able to get the sync version out of that.

src/index.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,10 @@ export function toGenerator<T>(promise: Promise<T> | QuansyncGenerator<T> | T):
138138
return promise
139139
return fromPromise(promise)()
140140
}
141+
142+
/**
143+
* @returns `true` if the current context is async, `false` otherwise.
144+
*/
145+
export function* getIsAsync(): Generator<typeof GET_IS_ASYNC, boolean, unknown> {
146+
return !!(yield GET_IS_ASYNC)
147+
}

test/index.test.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { expect, it, vi } from 'vitest'
2-
import { quansync, toGenerator } from '../src'
2+
import { getIsAsync, quansync, toGenerator } from '../src'
33
import { quansync as quansyncMacro } from '../src/macro'
44

55
it('basic', async () => {
@@ -282,3 +282,13 @@ it('call onYield hook', async () => {
282282
expect(() => run2.sync()).toThrowErrorMatchingInlineSnapshot(`[TypeError: custom error]`)
283283
await expect(run2.async()).resolves.toMatchInlineSnapshot(`"foo"`)
284284
})
285+
286+
it('getIsAsync', async () => {
287+
const fn = quansync(function* () {
288+
const isAsync: boolean = yield* getIsAsync()
289+
return isAsync
290+
})
291+
await expect(fn.async()).resolves.toBe(true)
292+
await expect(fn()).resolves.toBe(true)
293+
expect(fn.sync()).toBe(false)
294+
})

0 commit comments

Comments
 (0)