Files
Nim/nimcache/runnableExamples/asyncjs_examples_1.nim
github-actions[bot] 7014038f4a Deploy to GitHub pages
2025-12-29 13:02:56 +00:00

37 lines
1.1 KiB
Nim

#[
autogenerated by docgen
loc: /home/runner/work/Nim/Nim/lib/js/asyncjs.nim(205, 21)
rdoccmd: -r:off
]#
import std/assertions
import "/home/runner/work/Nim/Nim/lib/js/asyncjs.nim"
{.line: ("/home/runner/work/Nim/Nim/lib/js/asyncjs.nim", 205, 21).}:
from std/sugar import `=>`
proc fn(n: int): Future[int] {.async.} =
if n >= 7: raise newException(ValueError, "foobar: " & $n)
else: result = n * 2
proc asyncFact(n: int): Future[int] {.async.} =
if n > 0: result = n * await asyncFact(n-1)
else: result = 1
proc main() {.async.} =
block: # then
assert asyncFact(3).await == 3*2
assert asyncFact(3).then(asyncFact).await == 6*5*4*3*2
let x1 = await fn(3)
assert x1 == 3 * 2
let x2 = await fn(4)
.then((a: int) => a.float)
.then((a: float) => $a)
assert x2 == "8.0"
block: # then with `onReject` callback
var witness = 1
await fn(6).then((a: int) => (witness = 2), (r: Error) => (witness = 3))
assert witness == 2
await fn(7).then((a: int) => (witness = 2), (r: Error) => (witness = 3))
assert witness == 3