Most elegant way of returning from a threadsafe function? #1334
-
I'm trying to run a threadsafe function. Calling works fine, but I don't get how I can recieve a return value. If I understand this correctly, I need a callback which gets called inside JS with the return value. So basically:
But how would this look on the rust side of things?
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 9 replies
-
See here #1307 |
Beta Was this translation helpful? Give feedback.
-
hi @m1212e , I'm in kind of same situation and newbie with napi-rs. can you please share any working example for it. |
Beta Was this translation helpful? Give feedback.
-
I'm also new to napi-rs and am having trouble with this. I want to return a value to Rust from an async call const napi = require('./index.node')
napi.myCallback((value, resolve) => {
console.log(value)
resolve(42)
}) I have tried to copy the code exactly from the linked example: https://github.com/napi-rs/napi-rs/blob/main/examples/napi/src/threadsafe_function.rs#L145 use std::{thread, time::Duration};
#[macro_use]
extern crate napi_derive;
use napi::{
bindgen_prelude::*,
threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode, UnknownReturnValue},
JsString,
};
#[napi]
pub async fn tsfn_return_promise_timeout(
func: ThreadsafeFunction<u32, Promise<u32>>,
) -> Result<u32> {
use tokio::time::{self, Duration};
let promise = func.call_async(Ok(1)).await?;
let sleep = time::sleep(Duration::from_nanos(1));
tokio::select! {
_ = sleep => {
Err(Error::new(Status::GenericFailure, "Timeout".to_owned()))
}
value = promise => {
Ok(value? + 2)
}
}
} [dependencies]
# Default enable napi4 feature, see https://nodejs.org/api/n-api.html#node-api-version-matrix
napi = { version = "2.12.2", default-features = false, features = ["napi4", "tokio_full", "async", "full"] }
napi-derive = "2.12.2"
tokio = { version = "1.37.0", features = ["full"] }
[build-dependencies]
napi-build = "2.0.1" However I get the following errors:
and
Is the example up to date or am I missing something? |
Beta Was this translation helpful? Give feedback.
See here #1307