I'm trying to get my head around asynchronous programming and created a simple test program to play around with. The following code compiles and runs but it never seems to reach the "Done waiting" part in the wait procedure and I don't understand why. Is that code never reached because of the asyncCheck in test()? In that case, what does asyncCheck do?
proc wait(time:int){.async.} =
await sleepAsync(time)
echo "Done waiting:", time
proc test(){.async.} =
while true:
asyncCheck wait(1000)
waitFor test()
You know that wait returns Future[void] and not void, yes? From this knowledge, I can tell you that Future is an object that contains an error field which wait will set if any exception is raised inside it. If you just call wait(1000), you will ignore this error field, meaning if the asynchronous proc fails you won't know about it. asyncCheck does the error check for you.
I think this is the problem: The program can quit before running all async calls. Since not using await or waitFor will not block the current flow, the program will think it's done when it's done with everything that isn't asynchronously called. In the test proc, all that's done is asynchronously call wait instead of await it, so I doubt any progress is getting done. The solution in this case might be to use runForever (warning, you will get insane "Done waiting" spam if this works).
import asyncdispatch
proc wait(time: int) {.async.} =
await sleepAsync(time)
echo "Done waiting:", time
proc test() {.async.} =
while true:
asyncCheck wait(1000)
waitFor test()
runForever()