0

I am trying to execute the example of async-http-client doku. But unfortunately the code in the closure is not executed. Why?

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")
        }
    }
}

In the console I get: Program ended with exit code: 0. So it is executed with success. But there is no print statement in the console.

Thanks!

Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
Arnold Schmid
  • 163
  • 12

1 Answers1

1

It is because the main thread is getting executed before the request is done so no print statement will get called unless you ask the main thread to wait for the httpclient

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

Hadi Haidar
  • 337
  • 2
  • 13
  • Ok thanks. I saw it. I had to call it in such a manner: ``` import AsyncHTTPClient let httpClient = HTTPClient(eventLoopGroupProvider: .createNew) let response = try httpClient.get(url: "https://swift.org").wait() print (response) ``` So if I like to create a Swift Server script that makes remote calls, I have to handle them in a sequential(synchronous) way or how can I implement it in a asynchronous way? – Arnold Schmid Dec 21 '19 at 09:08
  • https://stackoverflow.com/questions/42568614/swift-wait-for-async-task?rq=1 check this way to wait for async tasks so you can run multiple tasks at the same time but you can't run it without waiting all tasks in the main thread – Hadi Haidar Dec 21 '19 at 09:18