Wendell
Wendell

Reputation: 546

Vapor (SwiftNIO) Interfacing with Async Methods

I am trying to use an async method from a 3rd party library to get a string result from a URL

public static func fetch(url: URL, completion: @escaping (Result<String, Error>) -> Void) {

inside a Vapor Swift request handler.

func getHandler(_ req: Request) -> EventLoopFuture<String> {}

Apple's SwiftNIO documentation introduces this:

func someAsyncOperation(args) -> EventLoopFuture<ResultType> {
    let promise = eventLoop.newPromise(of: ResultType.self)
    someAsyncOperationWithACallback(args) { result -> Void in
        // when finished...
        promise.succeed(result: result)
        // if error...
        promise.fail(error: error)
    }
    return promise.futureResult
}

But

the future result is returned before the async process has provided a value

How do we only return the promise only after it has value?

Upvotes: 1

Views: 246

Answers (1)

Johannes Weiss
Johannes Weiss

Reputation: 54071

You were looking at a super old NIO version. You can just write promise.completeWith(result).

See the newer docs at https://apple.github.io/swift-nio/docs/current/NIOCore/Structs/EventLoopPromise.html#/s:7NIOCore16EventLoopPromiseV12completeWithyys6ResultOyxs5Error_pGF

Upvotes: 1

Related Questions