summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorKonstantin Molchanov <kmolchanov@machinezone.com>2016-05-30 17:30:14 +0400
committerKonstantin Molchanov <kmolchanov@machinezone.com>2016-05-30 17:30:14 +0400
commit67ae65064c968ebcbc7cd147a80e177d9eb30351 (patch)
tree300794ead7d2b52b38269157ef0cce4a98420246
parent6556ec2ce049c705afab3d2749d9810d3cbc3a1a (diff)
downloadNim-67ae65064c968ebcbc7cd147a80e177d9eb30351.tar.gz
Stdlib: asyncdispatch: Add proc `all`.
-rw-r--r--lib/pure/asyncdispatch.nim24
1 files changed, 23 insertions, 1 deletions
diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim
index 139492916..2c7aaf2bf 100644
--- a/lib/pure/asyncdispatch.nim
+++ b/lib/pure/asyncdispatch.nim
@@ -355,6 +355,28 @@ proc `or`*[T, Y](fut1: Future[T], fut2: Future[Y]): Future[void] =
   fut2.callback = cb
   return retFuture
 
+proc all*[A](futs: seq[Future[A]]): Future[seq[A]] =
+  ## Returns a future which will complete once all futures in ``futs``
+  ## complete.
+  ##
+  ## The resulting future will hold the values of all awaited futures,
+  ## in the order they are passed.
+
+  var
+    retFuture = newFuture[seq[A]]("asyncdispatch.all")
+    retValues = newSeq[A](len(futs))
+    completedFutures = 0
+
+  for i, fut in futs:
+    fut.callback = proc(f: Future[A]) =
+      retValues[i] = f.read()
+      inc(completedFutures)
+
+      if completedFutures == len(futs):
+        retFuture.complete(retValues)
+
+  return retFuture
+
 type
   PDispatcherBase = ref object of RootRef
     timers: HeapQueue[tuple[finishAt: float, fut: Future[void]]]
@@ -1620,7 +1642,7 @@ proc recvLine*(socket: AsyncFD): Future[string] {.async.} =
       return
     add(result, c)
 
-proc callSoon*(cbproc: proc ()) = 
+proc callSoon*(cbproc: proc ()) =
   ## Schedule `cbproc` to be called as soon as possible.
   ## The callback is called when control returns to the event loop.
   getGlobalDispatcher().callbacks.enqueue(cbproc)