tasyncjs.nim 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. discard """
  2. output: '''
  3. x
  4. e
  5. done
  6. '''
  7. """
  8. #[
  9. xxx move this to tests/stdlib/tasyncjs.nim
  10. ]#
  11. import std/asyncjs
  12. block:
  13. # demonstrate forward definition for js
  14. proc y(e: int): Future[string] {.async.}
  15. proc e: int {.discardable.} =
  16. echo "e"
  17. return 2
  18. proc x(e: int): Future[void] {.async.} =
  19. var s = await y(e)
  20. if e > 2:
  21. return
  22. echo s
  23. e()
  24. proc y(e: int): Future[string] {.async.} =
  25. if e > 0:
  26. return await y(0)
  27. else:
  28. return "x"
  29. discard x(2)
  30. import std/sugar
  31. from std/strutils import contains
  32. var witness: seq[string]
  33. proc fn(n: int): Future[int] {.async.} =
  34. if n >= 7:
  35. raise newException(ValueError, "foobar: " & $n)
  36. if n > 0:
  37. var ret = 1 + await fn(n-1)
  38. witness.add $(n, ret)
  39. return ret
  40. else:
  41. return 10
  42. proc asyncFact(n: int): Future[int] {.async.} =
  43. if n > 0: result = n * await asyncFact(n-1)
  44. else: result = 1
  45. proc asyncIdentity(n: int): Future[int] {.async.} =
  46. if n > 0: result = 1 + await asyncIdentity(n-1)
  47. else: result = 0
  48. proc main() {.async.} =
  49. block: # then
  50. let x = await fn(4)
  51. .then((a: int) => a.float)
  52. .then((a: float) => $a)
  53. doAssert x == "14.0"
  54. doAssert witness == @["(1, 11)", "(2, 12)", "(3, 13)", "(4, 14)"]
  55. doAssert (await fn(2)) == 12
  56. let x2 = await fn(4).then((a: int) => (discard)).then(() => 13)
  57. doAssert x2 == 13
  58. let x4 = await asyncFact(3).then(asyncIdentity).then(asyncIdentity).then((a:int) => a * 7).then(asyncIdentity)
  59. doAssert x4 == 3 * 2 * 7
  60. block: # bug #17177
  61. proc asyncIdentityNested(n: int): Future[int] {.async.} = return n
  62. let x5 = await asyncFact(3).then(asyncIdentityNested)
  63. doAssert x5 == 3 * 2
  64. when false: # xxx pending bug #17254
  65. let x6 = await asyncFact(3).then((a:int) {.async.} => a * 11)
  66. doAssert x6 == 3 * 2 * 11
  67. block: # catch
  68. var reason: Error
  69. await fn(6).then((a: int) => (witness.add $a)).catch((r: Error) => (reason = r))
  70. doAssert reason == nil
  71. await fn(7).then((a: int) => (discard)).catch((r: Error) => (reason = r))
  72. doAssert reason != nil
  73. doAssert reason.name == "Error"
  74. doAssert "foobar: 7" in $reason.message
  75. echo "done" # justified here to make sure we're running this, since it's inside `async`
  76. discard main()