erkschE
Denoβ€’16mo agoβ€’
15 replies
erksch

RustyV8: Example of using PromiseResolver / async?

Is there an example using PromiseResolver? Because it uses a HandleScope, I'm unsure about how to reference it at a later point when async work has been done.

Could you provide an example of implementing a async simple sleep function, ideally by pushing an async task to the main Tokio runtime?

Problem:
borrowed data escapes outside of closure
`scope` escapes the closure body here


From JS:
await doRustAsync(5000);

Calling RS:
let export_do_rust_async = |scope: &mut v8::HandleScope,
                            _args: v8::FunctionCallbackArguments,
                            mut rv: v8::ReturnValue| {
  let millis = args.get(0).to_number(scope).unwrap().value() as u64;

  let resolver = v8::PromiseResolver::new(scope).unwrap();
  let promise = resolver.get_promise(scope);
  rv.set(promise.into());

  tokio::spawn(async move {
      // Do async work
      tokio::time::sleep(Duration::from_millis(millis)).await;
      promise.resolve()
  });
};


This Rust code obviously doesn't work, since:
1. the tokio runtime handle isn't available to the thread.
2. the promise/resolver uses scope, which is borrowed.
Was this page helpful?