Hello everybody, I don't know if this is the right place to ask for simple
things. I'm a complete novice to NIM and programming in general. I'm trying to
make a few http post requests. I managed to create the code to execute them
sequentially but then i wanted to speed it up. I attempted with async and with
spawn. In the end I managed to make it work with spawn but not with async. It
does not print the responses. Could you please help me to correct it and
understand? Any other feedback on how to improve both options (or better yet
combine them) would be really appreciated.
#sync with spawn import httpclient, json , times, threadpool
proc callStrategy (i : int) =
echo("request " & $i) let client = newHttpClient() client.headers =
newHttpHeaders({ "Content-Type": "application/json" })
let body = %*{
"Pid":i
} let response =
client.request("[https://reqres.in/api/strategy;](https://reqres.in/api/strategy),
httpMethod = HttpPost, body = $body) echo response.status echo response.body
echo("done " & $i)
proc loop (num: int) =
for i in 1..num:
echo "executing call number: " , i spawn callStrategy(i)
sync() # it took me some time to understand that here was correct, i originally
indented it on spawn level
let time = cpuTime() loop(10) #sync() #here also works. What is the difference?
echo "Time taken: ",cpuTime() - time
# async version import httpclient, asyncdispatch, json , times let time =
cpuTime()
proc callStrategy (i : int) {.async.} =
echo("request " & $i) let client = newAsyncHttpClient() client.headers =
newHttpHeaders({ "Content-Type": "application/json" })
let body = %*{
"Pid":i }
let response = await
client.request("[https://reqres.in/api/strategy;](https://reqres.in/api/strategy),
httpMethod = HttpPost, body = $body) echo response.status echo await
response.body echo("done " & $i)
proc loop (num: int) {.async.} =
echo "executing call number: " , num
for i in 1..num:
echo "executing call number: " , i discard callStrategy(i)
waitFor loop(10) echo "Time taken: ",cpuTime() - time