How to await ajaxget (or any ajax methods). I have this code:
import sugar, json, karax / [kajax, kdom], asyncjs
proc onGetObj(status: int, resp: kstring) =
let retVal = parseJson($resp)
echo retVal
proc getObj(sd: string) {.async} =
await ajaxGet("/api/v1/obj/" & sd & "/", @[state.header], onGetObj)
I get an error:
Error: type mismatch: got <void>
but expected one of:
proc await[T](f`gensym271651: Future[T]): T
What is the correct code?
ajaxGet takes a callback and is not awaitable. To do that the proc would need to return a Future[T]. You can wrap the ajax* procs to return a future like this:
import json, asyncjs, karax/[kajax]
type Response = object
status: int
body: cstring
proc ajaxGetAsync(url: cstring, headers: openarray[(cstring, cstring)]): Future[Response] =
return newPromise() do (resolve: proc(response: Response)):
ajaxGet(url, headers, proc (status: int, res: cstring) = resolve(Response(status: status, body: res)))
proc getObj(sd: string) {.async} =
let response = await ajaxGetAsync("/api/v1/obj/" & sd & "/", @[state.header])
let retVal = parseJson($response.body)
echo retVal