chore(example): add callback return promise (#1590)

This commit is contained in:
LongYinan 2023-05-16 11:05:37 +08:00 committed by GitHub
parent 5a3d10013b
commit 5bc098144c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 25 additions and 1 deletions

View file

@ -256,6 +256,8 @@ Generated by [AVA](https://avajs.dev).
export function callbackReturnPromise<T>(functionInput: () => T | Promise<T>, callback: (err: Error | null, result: T) => void): T | Promise<T>
export function callbackReturnPromiseAndSpawn(jsFunc: (arg0: string) => Promise<string>): Promise<string>
export function callLongThreadsafeFunction(callback: (...args: any[]) => any): void␊
export function callThreadsafeFunction(callback: (...args: any[]) => any): void␊

View file

@ -104,6 +104,7 @@ import {
CssStyleSheet,
asyncReduceBuffer,
callbackReturnPromise,
callbackReturnPromiseAndSpawn,
returnEitherClass,
eitherFromOption,
eitherFromObjects,
@ -348,6 +349,13 @@ test('callback function return Promise', async (t) => {
t.deepEqual(cbSpy.args, [['42']])
})
test('callback function return Promise and spawn', async (t) => {
const finalReturn = await callbackReturnPromiseAndSpawn((input) =>
Promise.resolve(`${input} world`),
)
t.is(finalReturn, 'Hello world 😼')
})
test('object', (t) => {
t.deepEqual(listObjKeys({ name: 'John Doe', age: 20 }), ['name', 'age'])
t.deepEqual(createObj(), { test: 1 })

View file

@ -246,6 +246,8 @@ export interface C {
export function callbackReturnPromise<T>(functionInput: () => T | Promise<T>, callback: (err: Error | null, result: T) => void): T | Promise<T>
export function callbackReturnPromiseAndSpawn(jsFunc: (arg0: string) => Promise<string>): Promise<string>
export function callLongThreadsafeFunction(callback: (...args: any[]) => any): void
export function callThreadsafeFunction(callback: (...args: any[]) => any): void

View file

@ -1,4 +1,4 @@
use std::env;
use std::{env, format};
use napi::{
bindgen_prelude::*,
@ -81,6 +81,18 @@ fn callback_return_promise<T: Fn() -> Result<JsUnknown>>(
}
}
#[napi(ts_return_type = "Promise<string>")]
pub fn callback_return_promise_and_spawn<F: Fn(String) -> Result<Promise<String>>>(
env: Env,
js_func: F,
) -> napi::Result<Object> {
let promise = js_func("Hello".to_owned())?;
env.spawn_future(async move {
let resolved = promise.await?;
Ok::<String, napi::Error>(format!("{} 😼", resolved))
})
}
#[napi]
pub fn capture_error_in_callback<C: Fn() -> Result<()>, E: Fn(Error) -> Result<()>>(
cb1: C,