-
Notifications
You must be signed in to change notification settings - Fork 31
/
async_utils.nim
45 lines (38 loc) · 1.61 KB
/
async_utils.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import
chronos, chronicles/chronos_tools
export
chronos_tools
template awaitWithTimeout*[T](operation: Future[T],
deadline: Future[void],
onTimeout: untyped): T =
let f = operation
await f or deadline
if not f.finished:
# If we don't wait for for the cancellation here, it's possible that
# the "next" operation will run concurrently to this one, messing up
# the order of operations (since await/async is not fair)
await cancelAndWait(f)
if f.cancelled: # It could have finished instead of getting cancelled
onTimeout
else:
await f # Await avoids extraneous exception effects
template awaitWithTimeout*[T](operation: Future[T],
timeout: Duration,
onTimeout: untyped): T =
awaitWithTimeout(operation, sleepAsync(timeout), onTimeout)
template awaitWithTimeout*(operation: Future[void],
deadline: Future[void],
onTimeout: untyped) =
let f = operation
await f or deadline
if not f.finished:
# If we don't wait for for the cancellation here, it's possible that
# the "next" operation will run concurrently to this one, messing up
# the order of operations (since await/async is not fair)
await cancelAndWait(f)
if f.cancelled: # It could have finished instead of getting cancelled
onTimeout
template awaitWithTimeout*(operation: Future[void],
timeout: Duration,
onTimeout: untyped) =
awaitWithTimeout(operation, sleepAsync(timeout), onTimeout)