Written in the book Nim in action: Typically, runForever, waitFor, and poll shouldn’t be used within async procedures, because they control the event loop directly. But, According to the example of the chat in the book, I tried to make a minor change and found it seems to be fine:
let serverAddr = paramStr(1)
var clientSocket = newAsyncSocket()
asyncCheck connect(clientSocket, serverAddr)
proc sendMsg(clientSocket: AsyncSocket){.async.}=
var messageFlowVar = spawn stdin.readLine()
while true:
if messageFlowVar.isReady():
let msg = createMessage("Anonymous", ^messageFlowVar)
asyncCheck clientSocket.send msg
messageFlowVar = spawn stdin.readLine()
asyncdispatch.poll() # I use poll() inside the async procedures
waitFor sendMsg(clientSocket)
I want to know, is this correct?
It might work but it's in general just a bad practice and I may disallow it completely in the future.
The reason it's a bad practice is that conceptutally async procedures shouldn't block. If you're calling poll then your async procedure will be blocked for the duration of that poll.
As far as this example goes, I hope that soon it will be possible to await a spawned procedure inside an async proc. This should simplify that example significantly.