nim-libp2p/tests/utils/async.nim

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

26 lines
764 B
Nim
Raw Normal View History

2024-08-07 21:05:33 +02:00
import chronos/futures, stew/results, chronos
2024-08-27 18:52:41 +02:00
import ./futures
proc toOk(future: Future[void]): Result[void, string] =
return results.ok()
proc toOk[T](future: Future[T]): Result[T, string] =
return results.ok(future.read())
proc toResult*[T](future: Future[T]): Result[T, string] =
if future.cancelled():
return results.err("Future cancelled/timed out.")
elif future.finished():
if not future.failed():
return future.toOk()
else:
return results.err("Future finished but failed.")
else:
return results.err("Future still not finished.")
2024-08-07 21:05:33 +02:00
proc waitForResult*[T](
2024-08-27 18:52:41 +02:00
future: Future[T], timeout = DURATION_TIMEOUT
2024-08-07 21:05:33 +02:00
): Future[Result[T, string]] {.async.} =
2024-08-27 18:52:41 +02:00
discard await future.withTimeout(timeout)
return future.toResult()