Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

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

Any guidance on how to use await / top level await #1606

Closed
kpko opened this issue Jul 31, 2023 · 1 comment
Closed

Any guidance on how to use await / top level await #1606

kpko opened this issue Jul 31, 2023 · 1 comment

Comments

@kpko
Copy link

kpko commented Jul 31, 2023

Hi,

in the long term I want to execute async c# functions in JavaScript. With the recent advantages with async/await and top level awaits I tried integrating these functions again. I understand there is no implicit task/promise conversion so I tried to use the engine.RegisterPromise() method to return a promise using a simple delay method.

As of my understanding this should create a promise that gets resolved in 5 seconds. The promise should be awaitable because of top-level awaits.

using Jint;

var engine = new Engine();
engine.SetValue("delay", (int seconds) =>
{
    var promise = engine.RegisterPromise();
    _ = Task.Delay(seconds * 1000)
        .ContinueWith(_ => promise.Resolve("success"), TaskContinuationOptions.OnlyOnRanToCompletion)
        .ContinueWith(_ => promise.Reject("failed"), TaskContinuationOptions.OnlyOnFaulted);

    return promise.Promise;
});
var val = engine.Evaluate("await delay(5)");
Console.WriteLine(val.UnwrapIfPromise());

This errors with 'Unexpected token' though. I tried wrapping everything in an async method:

var val = engine.Evaluate("(async () => await delay(5))()");
Console.WriteLine(val.UnwrapIfPromise());

But then I get the error 'System.InvalidOperationException: 'UnwrapIfPromise' called before Promise was settled'. This error seems to occur in the .Evaluate() line so I can't even work around that using a task completion source or something.

Is it possible to use await to await a task (converted to promise) in a script at this point? Or is what I'm trying simply not possible now (or ever)? Is there something I am missing?

Thank you in advance!

@Xicy
Copy link
Contributor

Xicy commented Jul 31, 2023

I tried to implement Task to Promise conversion in that PR #1567. It is working but it's not actually async, it's block the thread until resolve.
You can follow up in the pr. I hope PR helps to you :)

Repository owner locked and limited conversation to collaborators Jul 31, 2023
@lahma lahma converted this issue into discussion #1607 Jul 31, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants