status-im/nim-stew

The `?` operator from `stew/results` doesn't work in async procs

Opened this issue · 5 comments

zah commented

The async pragma is currently intercepting all return statements in the body of the async function in order to replace them with an operation that completes the returned Future.

The problem is that return statements appearing in expanded templates (such as ?) are not detected by this mechanism and this leads to compilation errors.

A possible solution would be to use a template called returnStatement(val) instead of return in ?. The async pragma will insert a local override for this template within the body of the async proc that will do the right thing.

can this be fixed on the async side? there's a few things in chronos that would benefit from Result support, for example to mark with type that things have gone from future to present - I also imagine it would make sense to extend ? and unify the Future and Result API's somewhat since Future mostly is a superset of Result.. @cheatfate ?

Can i get simple reproducible source to check async macro transformation with it?

kdeme commented

I've been hitting this too.

Here's a simple snippet:

proc resultTest(): Result[int, cstring] =
  ok(1)

proc asyncResultTest(): Future[Result[void, cstring]] {.async.} =
  let val = ? resultTest()
  await sleepAsync(1.seconds)
  return ok()

It would also be nice if we could do let val = ? await someAsyncProc() where someAsyncProc has Future[Result[...]] as return type. Or, like @arnetheduck mentions, somehow unify the API's.

@kdeme I'm not a fan of Future[Result[...]] because Result[T] is just a subset of Future[T]. Why not add more API for Future[T] in chronos to have all the features of Result[T] you want? Why we need to introduce this crutch?

Also i think its impossible to fix in chronos because ? uses typeof(result) and for async procedures typeof(result) is not a Result[T], but Future[T].