docs: add return Promise callback function

Fix https://github.com/napi-rs/napi-rs/issues/1128
This commit is contained in:
LongYinan 2022-04-14 00:02:06 +08:00
parent c553dcd4e0
commit cd9bb0c5d6
5 changed files with 21 additions and 1 deletions

View file

@ -40,6 +40,7 @@ Generated by [AVA](https://avajs.dev).
/** napi = { version = 2, features = ["serde-json"] } */␊
export function readFile(callback: (arg0: Error | undefined, arg1?: string | undefined | null) => void): void␊
export function returnJsFunction(): (...args: any[]) => any␊
export function callbackReturnPromise<T>(functionInput: () => T | Promise<T>, callback: (err: Error | null, result: T) => void): T | Promise<T>
export function dateToNumber(input: Date): number␊
export function chronoDateToMillis(input: Date): number␊
export function chronoDateAdd1Minute(input: Date): Date␊

View file

@ -2,6 +2,7 @@ import { exec } from 'child_process'
import { join } from 'path'
import test from 'ava'
import { spy } from 'sinon'
import {
DEFAULT_COST,
@ -89,6 +90,7 @@ import {
bufferPassThrough,
JsRepo,
asyncReduceBuffer,
callbackReturnPromise,
} from '../'
test('export const', (t) => {
@ -224,6 +226,21 @@ test('return function', (t) => {
})
})
test('function return Promise', async (t) => {
const cbSpy = spy()
await callbackReturnPromise<string>(() => '1', spy)
t.is(cbSpy.callCount, 0)
await callbackReturnPromise(
() => Promise.resolve('42'),
(err, res) => {
t.is(err, null)
cbSpy(res)
},
)
t.is(cbSpy.callCount, 1)
t.deepEqual(cbSpy.args, [['42']])
})
test('object', (t) => {
t.deepEqual(listObjKeys({ name: 'John Doe', age: 20 }), ['name', 'age'])
t.deepEqual(createObj(), { test: 1 })

View file

@ -30,6 +30,7 @@ export function optionOnly(callback: (arg0?: string | undefined | null) => void)
/** napi = { version = 2, features = ["serde-json"] } */
export function readFile(callback: (arg0: Error | undefined, arg1?: string | undefined | null) => void): void
export function returnJsFunction(): (...args: any[]) => any
export function callbackReturnPromise<T>(functionInput: () => T | Promise<T>, callback: (err: Error | null, result: T) => void): T | Promise<T>
export function dateToNumber(input: Date): number
export function chronoDateToMillis(input: Date): number
export function chronoDateAdd1Minute(input: Date): Date

View file

@ -53,7 +53,8 @@ fn return_js_function(env: Env) -> Result<JsFunction> {
#[napi(
ts_generic_types = "T",
ts_args_type = "functionInput: () => T | Promise<T>, callback: (err: Error | null, result: T) => void"
ts_args_type = "functionInput: () => T | Promise<T>, callback: (err: Error | null, result: T) => void",
ts_return_type = "T | Promise<T>"
)]
fn callback_return_promise<T: Fn() -> Result<JsUnknown>>(
env: Env,