When resume(returning:) doesn't seem returning

Hi there,

When resume(returning:) in withUnsafeThrowingContinuation block doesn't seem returning, what's the practice to debug it?

func foo(req: URLRequest) async throws -> Data {
  let result: Data = try await withUnsafeThrowingContinuation { c in
    let task = URLSession.shared.dataTask(with: req) { (data, _, error) in
      if let data = data {
        print("data")
        return c.resume(returning: data)
      } else {
        print("error")
        return c.resume(throwing: error ?? URLError(.badServerResponse))
      }
    }
    task.resume()
  }
  print("done")
  return result
}

I'm seeing this printing "data" but not "done" and wondering how to debug this function.

It works for me. Are you able to get the result from the call to foo?

There is no need to return the result of c.resume(returning: data) or c.resume(throwing: error ?? URLError(.badServerResponse)). Remove the return keyword on these lines.

Here's an example that works:

import Foundation

func makeRequest(request: URLRequest) async throws -> Data {
  let result: Data = try await withUnsafeThrowingContinuation { c in
    let task = URLSession.shared.dataTask(with: request) { (data, _, error) in
      if let data = data {
        print("data")
        c.resume(returning: data)
      } else {
        print("error")
        c.resume(throwing: error ?? URLError(.unknown))
      }
    }
    task.resume()
  }
  print("done")
  return result
}

Task {
    let url = URL(string: "https://dog.ceo/api/breeds/image/random")!
    let urlRequest = URLRequest(url: url)
    do {
        let result = try await makeRequest(request: urlRequest)
        print("result: \(result)")
    } catch {
        print("error: \(error)")
    }
}

RunLoop.main.run()

Output:

data
done
result: 98 bytes

No, because "done" never happens in my somewhat complicated code.

I know your working example works fine, and I have my own working example, too. But I'm seeing the case that "done" never happens therefore seems deadlock.

Maybe priority inversion or something is happening but couldn't figure it out so far.

If you want help, then you need to post an example that doesn't work, not one that does.

1 Like
Terms of Service

Privacy Policy

Cookie Policy