---
title: "Consume a JavaScript generator from C#"
url: https://recursiveai.org/oneecma/cookbook/consume-javascript-generator-from-csharp/
description: "Read JavaScript generator values one at a time from C# with OneEcma. Call next, inspect value and done, and close a generator early."
version: "1.1.1"
---

# Consume a JavaScript generator from C#

**OneEcma** is a free, open-source JavaScript interpreter for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneEcma) · [GitHub](https://github.com/recursive-ai-oss/oneecma-csharp) · [Docs](https://recursiveai.org/oneecma/docs/) · [Download example (.zip)](https://recursiveai.org/oneecma/cookbook/consume-javascript-generator-from-csharp/consume-javascript-generator-from-csharp.zip)

Read yielded values without collecting them into an array.

```shell
dotnet add package RecursiveAI.OneEcma
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneEcma;
var engine = new ScriptEngine();
var iterator = engine.Evaluate(
    "(function*(){ yield 10; yield 20; })()"
);
var next = engine.GetProperty(
    iterator.AsObject!, "next");
while (true)
{
    var step = engine.Call(next, iterator);
    var obj = step.AsObject!;
    var done = engine.GetProperty(obj, "done");
    if (done.AsBoolean) break;
    var value = engine.GetProperty(
        obj, "value");
    Console.WriteLine(value.AsNumber);
}
```

```text
10
20
```

Unzip [the example](https://recursiveai.org/oneecma/cookbook/consume-javascript-generator-from-csharp/consume-javascript-generator-from-csharp.zip), then `dotnet run`.

## The full program

```csharp
using RecursiveAI.OneEcma;

var engine = new ScriptEngine();
JsValue iterator = engine.Evaluate("""
    (function* () {
      try {
        yield 10;
        yield 20;
        return 99;
      } finally {
        globalThis.closed = true;
      }
    })()
    """);
JsValue next = engine.GetProperty(iterator.AsObject!, "next");
while (true)
{
    JsObject step = engine.Call(next, iterator).AsObject!;
    bool done = engine.GetProperty(step, "done").AsBoolean;
    double value = engine.GetProperty(step, "value").AsNumber;
    Console.WriteLine($"done={done}, value={value}");
    if (done) break;
}
Console.WriteLine($"closed={engine.Evaluate("closed").AsBoolean}");
```

`dotnet run` prints:

```text
done=False, value=10
done=False, value=20
done=True, value=99
closed=True
```

The full program displays the generator’s return value as well as its yielded values, then confirms that its `finally` block ran. A JavaScript exception raised while advancing the generator crosses into C# as `JsException`.

## Variations

Stop after the first value and call the generator’s `return` method to run its cleanup:

```csharp
using RecursiveAI.OneEcma;
var engine = new ScriptEngine();
var iterator = engine.Evaluate("""
(function* () {
  try { yield 1; yield 2; }
  finally { globalThis.closed = true; }
})()
""");
var next = engine.GetProperty(iterator.AsObject!, "next");
var first = engine.Call(next, iterator).AsObject!;
Console.WriteLine(engine.GetProperty(first, "value").AsNumber);
var close = engine.GetProperty(iterator.AsObject!, "return");
var last = engine.Call(close, iterator).AsObject!;
Console.WriteLine(engine.GetProperty(last, "done").AsBoolean);
Console.WriteLine(engine.Evaluate("closed").AsBoolean);
```

```text
1
True
True
```

## Related recipes

- [Call a JavaScript function](https://recursiveai.org/oneecma/cookbook/call-javascript-function/)
- [Await JavaScript promises](https://recursiveai.org/oneecma/cookbook/await-javascript-promises-from-dotnet/)

## The short answer

Keep the generator object returned by `Evaluate`, retrieve its `next` method, and invoke it with `engine.Call(next, iterator)`. Read `done` before consuming `value`. The snippet at the top prints only yielded values; the full program also shows the final return value.

The generator remains a JavaScript object owned by the engine. It is not automatically converted to `IEnumerable<T>`. This recipe uses the [public host API](https://recursiveai.org/oneecma/docs/host-api/) to advance it explicitly, so your C# code decides when to request another value and when to stop.

## What are iterators and generators in JavaScript?

An iterator produces result objects with `value` and `done` properties. A generator function, declared with `function*`, is one way to create such an iterator. Each `yield` suspends the function and supplies a value; calling `next()` resumes execution. MDN’s [iterators and generators guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) describes this protocol.

In the full program, evaluating the immediately invoked generator function creates its object. The first call to `next` reaches `yield 10`; the second reaches `yield 20`; the third completes the function with `return 99`. C# can inspect each result between calls. No array of all generated values is created by the host loop.

This is a synchronous generator. An asynchronous generator returns promises from its methods and needs promise handling before result inspection. Do not apply `AsObject` to an unresolved promise and expect the synchronous loop to await it.

## What is the difference between an iterator and a generator?

An iterator is the protocol; a generator is a language feature that implements it while preserving suspended function state. A handwritten iterator can expose the same `next` contract without using `yield`. C# callers can work with either if they follow that contract rather than assuming an array.

The method receiver matters. Retrieving `next` with `GetProperty` does not bind it to the object. The second argument to `engine.Call` must be the generator value itself. Passing `JsValue.Undefined` there loses the receiver that the generator method needs.

The loop also separates completion from value conversion. It checks `done` first in the snippet at the top, then reads the yielded number. A generic consumer should choose its accessor from the value’s type instead of assuming every JavaScript iterator yields numbers. The numeric accessor is appropriate here because every yielded value in the inline source is numeric.

## How do I read a JavaScript iterator without converting it to an array?

Call `next` only when you need another result. The full program retains one iterator and prints each step, including `done=True, value=99`. A generator’s final `return` value is not another yielded element; a consumer interested only in the sequence must stop when `done` becomes true, as the snippet at the top does.

If you stop early, close the generator deliberately. The variation calls its `return` method after consuming one value. For this generator, that enters `finally` and sets the `closed` flag. Merely breaking a C# loop is not a JavaScript `for...of` loop and does not invoke that method for you. The variation prints both completion and the flag so you can see the cleanup result.

Keep these calls on the thread that owns the engine, as the host API requires. Retaining an iterator does not make the engine thread-safe or turn each step into an independent execution context.
