Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(napi): add threadsafe deferred values #1306

Merged
merged 1 commit into from Oct 3, 2022

Conversation

devongovett
Copy link
Contributor

@devongovett devongovett commented Sep 11, 2022

Depends on #1303. See last commit for actual diff.

Closes #1304.

This adds an env.create_deferred method, which returns a new JsDeferred value and a JS Promise. The deferred can be used to resolve or reject the promise from a background thread, using a thread safe function. A function is passed to the resolve method of a deferred, which is called from the JS thread to create a JS value. This can return any type conforming to the ToNapiValue trait.

Example:

#[js_function(0)]
pub fn example(ctx: CallContext) -> Result<JsObject> {
  let (deferred, promise) = ctx.env.create_deferred()?;

  std::thread::spawn(move || {
    // ...
    deferred.resolve(|env| Ok(15));
  });

  Ok(promise)
}

I have also updated execute_tokio_future to utilize this new primitive instead of the existing internal promise module, which worked similarly but was more limited.

@Brooooooklyn Brooooooklyn changed the title Add threadsafe deferred values feat(napi): add threadsafe deferred values Oct 3, 2022
@Brooooooklyn Brooooooklyn merged commit 5541d65 into napi-rs:main Oct 3, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

General purpose Promise/Deferred
2 participants