This module implements types and macros for writing asynchronous code for the JS backend. It provides tools for interaction with JavaScript async API-s and libraries, writing async procedures in Nim and converting callback-based code to promises.
A Nim procedure is asynchronous when it includes the {.async.}
pragma. It should always have a Future[T]
return type or not have a return type at all. A Future[void]
return type is assumed by default.
This is roughly equivalent to the async
keyword in JavaScript code.
proc loadGame(name: string): Future[Game] {.async.} = # code
should be equivalent to
async function loadGame(name) { // code }
A call to an asynchronous procedure usually needs await
to wait for the completion of the Future
.
var game = await loadGame(name)
Often, you might work with callback-based API-s. You can wrap them with asynchronous procedures using promises and newPromise
:
proc loadGame(name: string): Future[Game] = var promise = newPromise() do (resolve: proc(response: Game)): cbBasedLoadGame(name) do (game: Game): resolve(game) return promise
Forward definitions work properly, you just need to always add the {.async.}
pragma:
proc loadGame(name: string): Future[Game] {.async.}
Nim currently generates async/await JavaScript code which is supported in modern EcmaScript and most modern versions of browsers, Node.js and Electron. If you need to use this module with older versions of JavaScript, you can use a tool that backports the resulting JavaScript code, as babel.
Future[T] = ref object future*: T
PromiseJs {...}{.importcpp: "Promise".} = ref object
proc newPromise[T](handler: proc (resolve: proc (response: T))): Future[T] {...}{. importcpp: "(new Promise(#))".}
proc newPromise(handler: proc (resolve: proc ())): Future[void] {...}{. importcpp: "(new Promise(#))".}
macro async(arg: untyped): untyped
© 2006–2018 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/asyncjs.html