diff --git a/Sources/NIO/EventLoopFuture.swift b/Sources/NIO/EventLoopFuture.swift index 0fdc64eae..3aea2cda0 100644 --- a/Sources/NIO/EventLoopFuture.swift +++ b/Sources/NIO/EventLoopFuture.swift @@ -919,16 +919,28 @@ extension EventLoopFuture { @inlinable public func fold(_ futures: [EventLoopFuture], with combiningFunction: @escaping (Value, OtherValue) -> EventLoopFuture) -> EventLoopFuture { - let body = futures.reduce(self) { (f1: EventLoopFuture, f2: EventLoopFuture) -> EventLoopFuture in - let newFuture = f1.and(f2).flatMap { (args: (Value, OtherValue)) -> EventLoopFuture in - let (f1Value, f2Value) = args - self.eventLoop.assertInEventLoop() - return combiningFunction(f1Value, f2Value) + func fold0() -> EventLoopFuture { + let body = futures.reduce(self) { (f1: EventLoopFuture, f2: EventLoopFuture) -> EventLoopFuture in + let newFuture = f1.and(f2).flatMap { (args: (Value, OtherValue)) -> EventLoopFuture in + let (f1Value, f2Value) = args + self.eventLoop.assertInEventLoop() + return combiningFunction(f1Value, f2Value) + } + assert(newFuture.eventLoop === self.eventLoop) + return newFuture } - assert(newFuture.eventLoop === self.eventLoop) - return newFuture + return body + } + + if self.eventLoop.inEventLoop { + return fold0() + } else { + let promise = self.eventLoop.makePromise(of: Value.self) + self.eventLoop.execute { + fold0().cascade(to: promise) + } + return promise.futureResult } - return body } }