Skip to content

Instantly share code, notes, and snippets.

@SPY
Created June 26, 2015 07:19
Show Gist options
  • Save SPY/d4a34cc0771308753430 to your computer and use it in GitHub Desktop.
Save SPY/d4a34cc0771308753430 to your computer and use it in GitHub Desktop.
proc get*(client: MemcacheAsyncClient, key: string): Future[string] =
let res = newFuture[string]()
client.sendCommand(CommandOpcode.Get, key = key.toRawData()).callback = proc(future: Future[Response]) {.closure, gcsafe.} =
let response = future.read()
if response.header.status == ResponseStatus.KeyNotFound:
res.fail(newException(KeyNotFoundError, "Key " & key & " is not found"))
else:
res.complete(response.value)
res
proc getAsync*(client: MemcacheAsyncClient, key: string): Future[string] {. async .} =
let response = await client.sendCommand(CommandOpcode.Get, key = key.toRawData())
if response.header.status == ResponseStatus.KeyNotFound:
raise newException(KeyNotFoundError, "Key " & key & " is not found")
else:
result = response.value
when isMainModule:
proc test(): Future[void] {. async .} =
const hello = "hello"
const world = "world"
var memcache = newMemcache()
await memcache.connect(host = "127.0.0.1", port = 11211.Port)
assert(await(memcache.add(hello, world)) == Added, "Key shouldn't exist before")
try: # works fine
let value = await memcache.get("unknown")
assert false
except KeyNotFoundError:
assert true
try: # fail with error
let value = await memcache.getAsync("unknown")
assert false
except KeyNotFoundError:
assert true
echo "All tests passed"
waitFor test()
raceback (most recent call last)
memcacheasync.nim(157) memcacheasync
asyncdispatch.nim(1545) waitFor
asyncdispatch.nim(983) poll
asyncdispatch.nim(1091) cb
asyncdispatch.nim(186) complete
asyncdispatch.nim(1199) cb
asyncnet.nim(256) recvIter
asyncdispatch.nim(186) complete
asyncdispatch.nim(1204) cb
asyncdispatch.nim(224) callback=
asyncdispatch.nim(1199) cb
memcacheasync.nim(72) waitForResponseIter
asyncdispatch.nim(186) complete
asyncdispatch.nim(1199) cb
memcacheasync.nim(82) sendCommandIter
asyncdispatch.nim(186) complete
asyncdispatch.nim(1211) cb
SIGSEGV: Illegal storage access. (Attempt to read from nil?)
Error: execution of an external program failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment