Greetings,
I wanted to use Redis in one of my projects. When trying to open a database asynchronously I always get the error database.nim(16, 27) Error: undeclared identifier: 'await'. No matter what I adjust in the code (like placing await in the most obviously known to be working places), it always ends with this error. Maybe I just made an error in my code, so I tried out the example given in the redis documentation:
import redis, asyncdispatch
## Open a connection to Redis running on localhost on the default port (6379)
let redisClient = openAsync()
## Set the key `nim_redis:test` to the value `Hello, World`
await redisClient.setk("nim_redis:test", "Hello, World")
## Get the value of the key `nim_redis:test`
let value = await redisClient.get("nim_redis:test")
assert(value == "Hello, World")
Even this super simple example code that is written by Nim developers does not work and throws the exact same error.
Environment:
Debian GNU/Linux 9.8 (stretch) on Windows 10 x86_64
4.4.0-17763-Microsoft #379-Microsoft Wed Mar 06 19:16:00 PST 2019 x86_64 GNU/Linux
____
Nim Compiler Version 0.19.4 [Linux: amd64]
Compiled at 2019-02-01
Copyright (c) 2006-2018 by Andreas Rumpf
git hash: b6d96cafc8bcad1f3d32f2910b25cd11a93f7751
active boot switches: -d:release
____
# Compilation command
nim cc database.nim
____
# gcc version
gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1)
P.S.: I searched the source code for the defition of await and could not find it anywhere. It is used everywhere but where is the first mention of it?
Sounds like a bug in Redis documentation, the await keyword is a used in {.async.} proc and only there. {.async.} is defined in asyncdispatch.
See asyncnet documentation https://nim-lang.org/docs/asyncnet.html
# Chat server
import asyncnet, asyncdispatch
var clients {.threadvar.}: seq[AsyncSocket]
proc processClient(client: AsyncSocket) {.async.} =
while true:
let line = await client.recvLine()
if line.len == 0: break
for c in clients:
await c.send(line & "\c\L")
proc serve() {.async.} =
clients = @[]
var server = newAsyncSocket()
server.setSockOpt(OptReuseAddr, true)
server.bindAddr(Port(12345))
server.listen()
while true:
let client = await server.accept()
clients.add client
asyncCheck processClient(client)
asyncCheck serve()
runForever()
Seems like the example should be rewritten to something similar to:
import redis, asyncdispatch
proc main(){.async.} =
## Open a connection to Redis running on localhost on the default port (6379)
let redisClient = waitFor redis.openAsync()
## Set the key `nim_redis:test` to the value `Hello, World`
asyncCheck redisClient.setk("nim_redis:test", "Hello, World")
## Get the value of the key `nim_redis:test`
let value = await redisClient.get("nim_redis:test")
assert(value == "Hello, World")
asyncCheck main()
Yeah, it's about time we change this to a nicer error. I updated the examples, thanks for flagging @Akito.
@mratsim By the way, never use waitFor in async procs. You should use await instead.