Skip to content

Instantly share code, notes, and snippets.

@SPY
Created June 28, 2015 20:19
Show Gist options
  • Save SPY/5b35c1d9582e3f30c15f to your computer and use it in GitHub Desktop.
Save SPY/5b35c1d9582e3f30c15f to your computer and use it in GitHub Desktop.
import asyncdispatch
type KeyNotFoundError* = object of IOError
proc get*(key: string): Future[string] =
let res = newFuture[string]()
sleepAsync(500).callback = proc(future: Future[void]) {.closure, gcsafe.} =
if key != "hello":
res.fail(newException(KeyNotFoundError, "Key " & key & " is not found"))
else:
res.complete("world")
res
proc getAsync*(key: string): Future[string] {. async .} =
await sleepAsync(500)
if key != "hello":
raise newException(KeyNotFoundError, "Key " & key & " is not found")
else:
result = "world"
proc test(): Future[void] {. async .} =
try:
let value = await get("unknown")
assert false
except KeyNotFoundError:
assert true
try: # fail with error
let value = await getAsync("unknown")
assert false
except KeyNotFoundError:
assert true
waitFor test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment