1

我正在尝试使用第 3 方库中的异步方法从 URL 获取字符串结果

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

在 Vapor Swift 请求处理程序中。

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

Apple 的SwiftNIO 文档介绍了这一点:

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
}

在异步进程提供值之前返回未来的结果

我们如何只在它具有价值之后才返回承诺?

4

1 回答 1

1

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

于 2022-02-16T07:01:24.617 回答