如何使用异步http客户端

How to use async-http-client

我正在尝试执行 async-http-client doku 的示例。但不幸的是闭包中的代码并没有被执行。为什么?

import AsyncHTTPClient

let httpClient = HTTPClient(eventLoopGroupProvider: .createNew)
httpClient.get(url: "https://swift.org").whenComplete { result in
    print (result)
    switch result {
    case .failure(let error):
        print("failure")
    case .success(let response):
        if response.status == .ok {
            print("success")
        } else {
            print("error in response")
        }
    }
}

在控制台中我得到:Program ended with exit code: 0。所以执行成功了。但是控制台没有打印语句。

谢谢!

这是因为主线程在请求​​完成之前执行,所以不会调用打印语句,除非您要求主线程等待 httpclient

https://github.com/swift-server/async-http-client/issues/129