Get a promise’s eventual result from embedded JavaScript in C#.
dotnet add package RecursiveAI.OneEcmaRequires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.
using RecursiveAI.OneEcma; var engine = new ScriptEngine(); var result = engine.Await( engine.Evaluate("Promise.resolve(42)")); Console.WriteLine(result.AsNumber);
42Unzip the example, then dotnet run.
Full program
The host function load starts a C# task. JavaScript doubles its result; the program then exercises rejection and a promise with nothing that can resolve it. All inputs are inline.
using RecursiveAI.OneEcma; var engine = new ScriptEngine(); var realm = engine.MainRealm; engine.DefineGlobalFunction("load", 0, (_, _) => JsMarshal.FromTask(realm, "load", async () => { await Task.Yield(); return 21; }, (_, number) => JsValue.FromNumber(number))); var result = engine.Await(engine.Evaluate("load().then(n => n * 2)")); Console.WriteLine($"fulfilled: {result.AsNumber}"); foreach (string source in new[] { "Promise.reject(new Error('no data'))", "new Promise(() => {})" }) { try { engine.Await(engine.Evaluate(source)); } catch (JsException error) { Console.WriteLine(error.Message); } }
dotnet run prints:
fulfilled: 42 Error: no data Error: The promise never settles: no job is queued and no host operation is running
A rejected promise or one that cannot settle throws JsException; the catches print both messages without ending the program early.
Variations
Use C# await with EvaluateAsync rather than blocking the calling thread:
using RecursiveAI.OneEcma; var engine = new ScriptEngine(); var result = await engine.EvaluateAsync(""" (async () => { const number = await Promise.resolve(20); return number + 22; })() """); Console.WriteLine(result.AsNumber);
42Related recipes
The short answer
Use engine.Await(engine.Evaluate(source)) to run JavaScript that returns a promise and receive its fulfillment value in C#. The engine pumps promise jobs and registered host-task continuations while it waits. Use await engine.EvaluateAsync(source) when the C# caller should not block. Both paths produce a JsValue, not a JavaScript promise wrapper that your application must poll.
For an asynchronous C# function called by JavaScript, register a host function and return JsMarshal.FromTask. Pass a factory that starts the task, plus a converter from the task’s result to a JavaScript value. The full program does this with a task returning a number. It needs no network connection, timer service or external file.
How do you await a promise in JavaScript?
Inside JavaScript, put await in an async function, as the variation does. Calling that function produces a promise. At the C# boundary, EvaluateAsync waits for its fulfillment and returns the final number. These are two separate waits: JavaScript waits for its input, and the host waits for the async function’s result.
The MDN promise guide explains pending, fulfilled and rejected states. In an embedded engine, there is also a host responsibility: something must run the queued reactions. OneEcma supplies that through Await, EvaluateAsync and the job-pump APIs, rather than through a browser event loop.
Choose the synchronous Await path when blocking the calling thread is acceptable. The full program uses it to keep the owning console thread in control throughout the host-task example. Choose the async path when the application needs a nonblocking wait, and serialize access to that engine: an engine is not thread-safe.
How do you catch errors with async/await?
Catch JsException around the evaluation and wait, not just around the later read of AsNumber. A JavaScript rejection can reach C# during evaluation because evaluation also drains jobs. The full program covers both operations with the same try block and prints the actual rejection message.
A task returned through JsMarshal.FromTask becomes a promise. According to the pinned host API documentation, synchronous throws, faulted tasks and canceled tasks become rejected promises with the .NET exception represented as a script Error. Don’t turn a failure into a successful numeric return unless that is your application’s intended contract. The engine also throws for unhandled rejections by default.
Why is JavaScript await not waiting?
With synchronous Evaluate, returning from the call does not mean an outstanding host task has finished. RunJobs drains queued jobs; RunUntilIdle additionally waits for host tasks and runs their continuations. Await is the appropriate choice when you need one particular promise’s value. Merely inspecting a task’s status in a loop does not replace those operations.
Keep host methods inside the task bridge. While a bridged async host method runs, the engine’s synchronization context routes its await continuations back through the engine pump, allowing callbacks into script there. Don’t call the engine from an arbitrary worker-thread continuation or poll unrelated tasks expecting the engine to discover them.
A permanently pending JavaScript promise is a different problem. In the full program, its executor queues no work and starts no host operation. Await throws the displayed “never settles” error instead of hanging. That check is not a timeout for a host operation that is still running. Cancellation can be passed to the wait APIs; it is distinct from detecting that nothing remains capable of settling a promise.