How quansync works: Creating sync/async APIs
mainThe quansync function allows you to create a single function that can be executed either synchronously or asynchronously. You can define this behavior in two ways:
- Implementation Object: Provide an object with
syncandasyncproperties containing the respective implementations. - Generator Function: Provide a generator function. Inside the generator, use
yield*to call other quansync functions. This allows the logic to be shared between both modes.
Once created, you can access the synchronous version via .sync() and the asynchronous version via .async() (or by awaiting the function directly).
import fs from 'node:fs'
import { quansync } from 'quansync'
// Method 1: Implementation Object
const readFile = quansync({
sync: (path: string) => fs.readFileSync(path),
async: (path: string) => fs.promises.readFile(path),
})
// Method 2: Generator Function
const myFunction = quansync(function* (filename) {
// Use `yield*` to call another quansync function
const code = yield* readFile(filename, 'utf8')
return `// some custom prefix\n${code}`
})
// Usage
const result = myFunction.sync('./some-file.js') // Sync
const asyncResult = await myFunction.async('./some-file.js') // Async