napi-rs Docs

Task

Task

Addon modules often need to leverage async helpers from libuv as part of their implementation. This allows them to schedule work to be executed asynchronously so that their methods can return in advance of the work being completed. This allows them to avoid blocking overall execution of the Node.js application.

You can use Env::spawn to spawn a defined Task into libuv thread pool. See example in Reference.

Expect compute and resolve, you can also provide reject method to do some clean up when Task ran into error, like unref some object:

struct CountBufferLength {
data: Ref<JsBufferValue>,
}
impl CountBufferLength {
pub fn new(data: Ref<JsBufferValue>) -> Self {
Self { data }
}
}
impl Task for CountBufferLength {
type Output = usize;
type JsValue = JsNumber;
fn compute(&mut self) -> Result<Self::Output> {
if self.data.len() == 10 {
return Err(Error::from_reason("len can't be 5".to_string()));
}
Ok((&self.data).len())
}
fn resolve(self, env: Env, output: Self::Output) -> Result<Self::JsValue> {
self.data.unref(env)?;
env.create_uint32(output as _)
}
fn reject(self, env: Env, err: Error) -> Result<Self::JsValue> {
self.data.unref(env)?;
Err(err)
}
}
Edit this page on GitHub