Skip to content

Add an asyncFor macro or smthng. #19272

Open
@Q-Master

Description

@Q-Master

There are many cases when it is good to asyncronously iterate through some iterator, especially in database drivers. It will be a good idea to make some sort of asyncFor macro to asyncmacros.nim to make this possible.
Something like this:

macro asyncFor*(iterClause: untyped, body: untyped): untyped =
  if iterClause.kind != nnkInfix or iterClause[0] != ident("in"):
    error("expected `x in y` after for")

  let cursor = iterClause[2]
  let itemName = iterClause[1]
  result = quote do:
    while true:
      let future = next(`cursor`)
      yield future
      if future.failed: 
        raise future.readError()
      let tu = future.read()
      if not tu[0]: break
      let `itemName` {.inject.} = tu[1]
      `body`

I've got that code somewhere from the forums and it seems working. The only thing is one should implement the proc next(cusor) with tuple[bool, T] as a result. There might be a better idea to implement, something like throwing an exception in the next() proc when iteration stopped.

Metadata

Metadata

Assignees

No one assigned

    Labels

    AsyncEverything related to Nim's asyncFeature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions