# TODO: These should be added to the Chronos's asyncfutures2 module # See https://github.com/status-im/nim-chronos/pull/339 import chronos proc firstCompletedFuture*(futs: varargs[FutureBase]): Future[FutureBase] = ## Returns a future which will complete and return completed FutureBase, ## when one of the futures in ``futs`` is completed. ## ## If the argument is empty, the returned future FAILS immediately. ## ## On success, the returned Future will hold the completed FutureBase. ## ## If all futures fail naturally or due to cancellation, the returned ## future will be failed as well. ## ## On cancellation, futures in ``futs`` WILL NOT BE cancelled. var retFuture = newFuture[FutureBase]("chronos.firstCompletedFuture()") # Because we can't capture varargs[T] in closures we need to create copy. var nfuts = @futs # If one of the Future[T] already finished we return it as result for fut in nfuts: if fut.completed(): retFuture.complete(fut) return retFuture if len(nfuts) == 0: retFuture.fail(newException(ValueError, "Empty Future[T] list")) return var failedFutures = 0 var cb: proc(udata: pointer) {.gcsafe, raises: [Defect].} cb = proc(udata: pointer) {.gcsafe, raises: [Defect].} = if not(retFuture.finished()): var res: FutureBase var rfut = cast[FutureBase](udata) if rfut.completed: for i in 0..