# Asynchronous Programming in Mojo

**URL:** <https://forum.modular.com/t/asynchronous-programming-in-mojo/3544>\
**Category:** Language Design\
**Created:** [October 2, 2026, 4:36pm UTC](https://forum.modular.com/t/asynchronous-programming-in-mojo/3544 "2026-10-02T16:36:17Z")\
**Posts on this page:** 1\
**Showing post:** 31

<div class="post-metadata">

**Author:** ![owenhilyard](https://sea1.discourse-cdn.com/flex001/user_avatar/forum.modular.com/owenhilyard/32/41_2.png) [@owenhilyard](https://forum.modular.com/u/owenhilyard)\
**Post date:** [October 15, 2026, 3:58pm UTC](https://forum.modular.com/t/asynchronous-programming-in-mojo/3544/31 "2026-10-15T15:58:44Z")

</div>

> [@Steffi](#):
>
> The coroutine stores a resume function pointer and a callback

Does this leave the door open for typestate-based coroutines? Ideally, I’d like to avoid having the function pointer for “simple” async constructs where it’s acting as more of a state machine abstraction. Especially for network infrastructure code, it’s very reasonable to have a limited number of states such that every coroutine in each of a group of lists or other lookup-optimized data structures is in the same state. Forcing the function pointers in there means adding the pointer in a case where the there’s no need for it.

```mojo
from std.ffi.unsafe_union import UnsafeUnion

@fieldwise_init
struct States(Equatable, Hashable, ImplicitlyCopyable, Movable):
    """
    a -> b;
    b -> c;
    c -> c;
    c -> e;
    b -> d;
    d -> e;
    """

    var _value: UInt8

    comptime a = Self(0)
    comptime b = Self(1)
    comptime c = Self(2)
    comptime d = Self(3)
    comptime e = Self(4)

@fieldwise_init
struct IAmNotImportant(
    Defaultable, Equatable, Hashable, ImplicitlyCopyable, Movable
):
    var _value: UInt8

struct TypestateBasedCoroutine[state: States]:
    comptime WithState[state: States] = TypestateBasedCoroutine[state]

    var state: IAmNotImportant

    comptime next_state_function = Self.next_state_a if Self.state == States.a else Self.next_state_b if Self.state == States.b else Self.next_state_c if Self.state == States.c else Self.next_state_d

    def __init__ (
        var self, var state: IAmNotImportant
    ) where Self.state == States.a:
        self.state = state

    def next_state_a(var self) -> Self.WithState[States.b]:
        ...

    def next_state_b(
        var self,
    ) -> Either[Self.WithState[States.c], Self.WithState[States.e]]:
        ...

    def next_state_c(
        var self,
    ) -> Either[Self.WithState[States.c], Self.WithState[States.e]]:
        ...

    def next_state_d(var self) -> Self.WithState[States.e]:
        ...

    def __deinit__ (var self) where Self.state == States.e:
        ...

struct TypeErasedCoroutine(Equatable, Hashable, ImplicitlyCopyable, Movable):
    var state: States
    var data: UnsafeUnion[
        TypestateBasedCoroutine[States.a],
        TypestateBasedCoroutine[States.b],
        TypestateBasedCoroutine[States.c],
        TypestateBasedCoroutine[States.d],
        TypestateBasedCoroutine[States.e],
    ]

    def __init__ (var self, var state: States, var data: IAmNotImportant):
        self.state = state
        self.data = {TypestateBasedCoroutine[States.a](state=data)}

    def next_state(mut self) -> Bool:
        """Returns true if the coroutine has reached its final state, false otherwise."""
        if self.state == States.a:
            var coroutine = self.data.get(TypestateBasedCoroutine[States.a])
            var next_coroutine = coroutine.next_state_a()
            self.state = States.b
            self.data = {next_coroutine}
        elif self.state == States.b:
            var coroutine = self.data.get(TypestateBasedCoroutine[States.b])
            var next_coroutine = coroutine.next_state_b()
            if next_coroutine.is_left():
                self.state = States.c
                self.data = {next_coroutine.left()}
            else:
                self.state = States.e
                self.data = {next_coroutine.right()}
        elif self.state == States.c:
            var coroutine = self.data.get(TypestateBasedCoroutine[States.c])
            var next_coroutine = coroutine.next_state_c()
            if next_coroutine.is_left():
                self.state = States.c
                self.data = {next_coroutine.left()}
            else:
                self.state = States.e
                self.data = {next_coroutine.right()}
                return True
        elif self.state == States.d:
            var coroutine = self.data.get(TypestateBasedCoroutine[States.d])
            var next_coroutine = coroutine.next_state_d()
            self.state = States.e
            self.data = {next_coroutine}
            return True
        else:
            panic("Cannot transition from state e")
        
        return False

    def __deinit__ (var self):
        ...

```

The main benefit of this as the “base representation” is that library code can build the common representations (jump tables, callback function pointer, etc) from this with no loss in performance, which opens up experimentation in library land without extra compiler work.

> [@Nick](#):
>
> > [How to express] APIs that are generic over sync and async.
> 
> IMO this will be a major question that needs answering after the `async` MVP lands. I hope we can figure out the right solution to “async generics” before the standard library (and broader ecosystem) stablises its `async` APIs.

I think this might need to be something that is considered as part of coroutines, because the two options I can think of for making “async generic” code at a syntax level are either to force all code to be “async correct” or to make it so that the `generic` dialect is less powerful than the `async` dialect and is forced to implicitly await anything with an ` __await__ ` when it is created. Zig has an interface which gets rid of function coloring, but it doesn’t appear to really allow you to write code which is fully generic over whether or not you’re doing async IO without duplicating most function call sites.

---

_[View the full topic](https://forum.modular.com/t/asynchronous-programming-in-mojo/3544)._
