DenoDDeno
Powered by
erkschE
Denoβ€’2y 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
borrowed data escapes outside of closure
`scope` escapes the closure body here


From JS:
await doRustAsync(5000);
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()
  });
};
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.
Deno banner
DenoJoin
Chat about Deno, a modern runtime for JavaScript and TypeScript.
20,934Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

RustyV8: Example of creating a TypedArray?
Kalleby SantosKKalleby Santos / help
2y ago
AsyncLocalStorage without `node:async_hooks`
jonJjon / help
2y ago
Embedding RustyV8: Fatal JavaScript out of memory: Reached heap limit
erkschEerksch / help
2y ago
Using JsRuntime in an async context
kiakoKkiako / help
16mo ago