fix(napi): asynchronous functions can return any errors (#2165)

* feat(napi): asynchronous functions can return any errors as long as they implement the Into<Error> trait.

* chore: use impl Into<Error>
This commit is contained in:
Jade-fu 2024-07-04 14:47:32 +08:00 committed by GitHub
parent c61aa20dfe
commit 2265ca3e1a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 8 additions and 3 deletions

View File

@ -103,7 +103,12 @@ impl TryToTokens for NapiFn {
let call = if self.is_ret_result {
quote! { #receiver(#(#arg_names),*).await }
} else {
quote! { Ok(#receiver(#(#arg_names),*).await) }
let ret_type = if let Some(t) = &self.ret {
quote! { #t }
} else {
quote! { () }
};
quote! { Ok(#receiver(#(#arg_names),*).await) as napi::bindgen_prelude::Result<#ret_type> }
};
quote! {
napi::bindgen_prelude::execute_tokio_future(env, async move { #call }, move |env, #receiver_ret_name| {

View File

@ -150,7 +150,7 @@ impl<Data: 'static + Send, R: 'static + FnOnce(sys::napi_env, Data) -> Result<sy
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub fn execute_tokio_future<
Data: 'static + Send,
Fut: 'static + Send + Future<Output = Result<Data>>,
Fut: 'static + Send + Future<Output = std::result::Result<Data, impl Into<Error>>>,
Resolver: 'static + FnOnce(sys::napi_env, Data) -> Result<sys::napi_value>,
>(
env: sys::napi_env,
@ -169,7 +169,7 @@ pub fn execute_tokio_future<
.resolve(env.raw(), v)
.map(|v| unsafe { JsUnknown::from_raw_unchecked(env.raw(), v) })
}),
Err(e) => deferred.reject(e),
Err(e) => deferred.reject(e.into()),
}
};