On Wed, Sep 16, 2020 at 8:56 AM Yao Xiao <yao...@chromium.org> wrote:
>
> Hi v8-users,
>
> I'm new to v8.
>
> For a "script" that has a call to a sync function that returns an integer, I 
> figured I could do the following to get the result in C++:
>
> v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();
> int result_int = result->Int32Value(context).FromJust();
>
> I'm wondering if there's a way to get (i.e. make C++ aware of) the return 
> value an async function? I tried to use await but it seems that the script 
> won't compile.

You can attach your own .then and .catch callbacks if the script's
return value is a promise (which is what the return value of an async
function really is):

  if (result->IsPromise()) {
    Local<Promise> promise = result.As<Promise>();
    if (promise->State() == Promise::kPending) {
      Local<Function> resolve = Function::New(context,
Resolve).ToLocalChecked();
      Local<Function> reject = Function::New(context, Reject).ToLocalChecked();
      promise = promise.Then(resolve, reject).ToLocalChecked();
  } else {
    result = promise->Result();  // note: distinguish between
kFulfilled and kRejected
    // ...
  }

You'll need to pump the event loop and/or the microtask queue in order
for the promise to resolve.

Apropos the await keyword, that isn't accepted at the top-level scope
(outside an async function) unless you're executing the script as an
ES module and the --harmony_top_level_await flag is set.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-SadnFfU7oaG%2BMMnrZ_teaffm7toFjOC1372e%2BMmqXZA%40mail.gmail.com.

Reply via email to