【问题标题】:How to use async-http-client如何使用 async-http-client
【发布时间】:2020-04-13 12:45:54
【问题描述】:

我正在尝试执行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。所以它执行成功。但是控制台中没有打印语句。

谢谢!

【问题讨论】:

    标签: swift swift-nio


    【解决方案1】:

    这是因为主线程在请求​​完成之前就被执行了,所以除非你让主线程等待 httpclient,否则不会调用 print 语句

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

    【讨论】:

    • 好的,谢谢。我看到了。我不得不以这样的方式调用它:``` import AsyncHTTPClient let httpClient = HTTPClient(eventLoopGroupProvider: .createNew) let response = try httpClient.get(url: "swift.org").wait() print (response) ``` 所以如果我喜欢要创建进行远程调用的 Swift Server 脚本,我必须以顺序(同步)方式处理它们,或者如何以异步方式实现它?
    • stackoverflow.com/questions/42568614/…检查这种方式等待异步任务,这样你就可以同时运行多个任务,但你不能在不等待主线程中的所有任务的情况下运行它
    猜你喜欢
    • 1970-01-01
    • 2016-09-07
    • 2014-01-26
    • 2020-04-25
    • 1970-01-01
    • 2016-11-09
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多