'async' call in a function that does not support concurrency - swift

I'm trying to use async/await with Swift 5.5. I have my async function, but whenever I try to call it, I get this error:
'async' call in a function that does not support concurrency
Here's the code sample:
class TryThis {
func getSomethingLater(_ number: Double) async -> String {
// test - sleep for 3 seconds, then return
Thread.sleep(forTimeInterval: 3)
return String(format: ">>>%8.2f<<<", number)
}
}
let tryThis = TryThis()
let result = await tryThis.getSomethingLater(3.141592653589793238462)
print("result: \(result)")
What's the solution for this??

The answer here is that the "await getSomethingLater" must be called from an async context. Literally that means changing this:
let result = await tryThis.getSomethingLater(3.141592653589793238462)
print("result: \(result)")
into this:
Task {
let result = await tryThis.getSomethingLater(3.141592653589793238462)
print("result: \(result)")
}
So the whole thing becomes:
class TryThis {
func getSomethingLater(_ number: Double) async -> String {
// test - sleep for 3 seconds, then return
Thread.sleep(forTimeInterval: 3)
return String(format: ">>>%8.2f<<<", number)
}
}
let tryThis = TryThis()
Task {
let result = await tryThis.getSomethingLater(3.141592653589793238462)
print("result: \(result)")
}
Here's the output:
result: >>> 3.14<<<
There's great info in the Meet async/await in Swift video from WWDC21.

When calling async code (including actor fields) from non-async code, you have to wrap it in a Task:
Task {
let result = await tryThis.getSomethingLater(3.141592653589793238462)
print("result: \(result)")
}
If you need it to escape that async context, you can use traditional callbacks:
func awaitedResult(callback: (String) -> Void) {
Task {
let result = await tryThis.getSomethingLater(3.141592653589793238462)
callback(result)
}
}
awaitedResult { result in
print("result: \(result)")
}
Swift by Sundell also offers some alternatives involving Combine
Further reading: Concurrency — The Swift Programming Language (Swift 5.5)

The original error is produced because "top-level" await is not yet supported in Swift (that is, code at the global scope).
The error just means you need to provide the async function with an asynchronous context, like using Task, Task.detached or a TaskGroup, depending on the behaviour you want.
Task.detached {
let result = await tryThis.getSomethingLater(3.141592653589793238462)
print("result: \(result)")
}
However, your code snippet should work in the future when top-level await is eventually proposed, implemented and supported.
Top-level await support was mentioned as part of the original proposal for async/await SE-0296.

In my case I just refactored the:
async { some-code-which-can-take-some-time }
with:
Task { some-code-which-can-take-some-time }

This error occurs when you’ve tried to call an async function from a synchronous function, which is not allowed in Swift – asynchronous functions must be able to suspend themselves and their callers, and synchronous functions simply don’t know how to do that.
func doAsyncWork() async {
print("Doing async work")
}
func doRegularWork() {
Task {
await doAsyncWork()
}
}
doRegularWork()
Reference here

Related

How to ignore async let throws error when save response in tuple?

i have a code like this:
Task {
async let configsReq = self.interactor.getConfigs()
async let optionsReq = self.interactor.getOptions()
async let updateStateReq = self.interactor.getAppUpdateState()
async let contactsReq = self.interactor.getContactOptions()
var config: Config?
var options: AvailableOptions?
var updateState: UpdateType?
var contacts: ContactOptions?
do {
config = try await configsReq
} catch {
config = nil
}
do {
options = try await optionsReq
} catch {
options = nil
}
do {
updateState = try await updateStateReq
} catch {
updateState = nil
}
do {
contacts = try await contactsReq
} catch {
contacts = nil
}
self.goToNextPage()
}
in this case it does not matter for me that the requests get correct response or throws error. i don't want to block user to get correct response.
And also I want to make sure that all my requests are answered (correct or error response) to take the user to the next page
how can i write these codes cleaner and better with new swift concurrency?
i tried like this (but i could not get match error to each related request):
Task {
async let configs = self.interactor.getConfigs()
async let options = self.interactor.getOptions()
async let updateState = self.interactor.getAppUpdateState()
async let contacts = self.interactor.getContactOptions()
do {
let array = try await [configs, options, updateState, contacts]
} catch {
print(error)
}
}
If I understand the question correctly, you want to:
“match error to each related request”, but that
you want to proceed regardless of success or failure, as it “does not matter for me that the requests get correct response or throws error”.
If that is the pattern you are looking for, I might suggest using Task result:
async let configsReq = Task { try await interactor.getConfigs() }
async let optionsReq = Task { try await interactor.getOptions() }
async let stateReq = Task { try await interactor.getAppUpdateState() }
async let contactsReq = Task { try await interactor.getContactOptions() }
let config = await configsReq.result
let options = await optionsReq.result
let state = await stateReq.result
let contacts = await contactsReq.result
goToNextPage(config: config, options: options, state: state, contacts: contacts)
Or, more concisely:
async let configs = Task { try await interactor.getConfigs() }
async let options = Task { try await interactor.getOptions() }
async let state = Task { try await interactor.getAppUpdateState() }
async let contacts = Task { try await interactor.getContactOptions() }
await goToNextPage(config: configs.result, options: options.result, state: state.result, contacts: contacts.result)
Where goToNextPage might be defined as:
func goToNextPage(
config: Result<Config, Error>,
options: Result<AvailableOptions, Error>,
state: Result<UpdateType, Error>,
contacts: Result<ContactOptions, Error>
) { … }
That way, goToNextPage can look at the .success or .failure for each, to retrieve either the value or error associated with each of the four requests.
Needless to say, you also could have four properties for these four requests, and then goToNextPage could refer to those, rather than taking them as parameters to the method. It’s functionally the same thing, but you have to decide either local vars that are passed to the next method or update properties that are accessed by the next method.
You asked:
… if we don't want to use Result anymore, how can do that?
Yes, we do not use Result very much, anymore, as that was historically a pattern for returning either value or error in traditional asynchronous patterns, and nowadays we try a series of tasks, catch thrown errors, but generally early exit once one of them fails.
But if you really want to capture the success and failure for each of the four concurrent requests, then Result encapsulates that quite well.
I would make a little helper that helps wrap the error into a Result:
extension Result {
init(asyncCatching block: () async throws -> Success) async where Failure == Error {
do {
self = .success(try await block())
} catch {
self = .failure(error)
}
}
}
In case of errors, you even get the Error object for each getXXX method, rather than just a nil. Of course, if you really just want a nil, you can write a helper that returns optionals instead.
// this is essentially like refactoring out the repeated parts of your first code
func asyncCatchWithNil<Result>(function: () async throws -> Result) async -> Result? {
do {
return try await function()
} catch {
return nil
}
}
Then you could do:
Task {
async let configs = Result(asyncCatching: self.interactor.getConfigs)
async let options = Result(asyncCatching: self.interactor.getOptions)
async let updateState = Result(asyncCatching: self.interactor.getAppUpdateState)
async let contacts = Result(asyncCatching: self.interactor.getContactOptions)
/* or
async let configs = asyncCatchWithNil(function: self.interactor.getConfigs)
async let options = asyncCatchWithNil(function: self.interactor.getOptions)
async let updateState = asyncCatchWithNil(function: self.interactor.getAppUpdateState)
async let contacts = asyncCatchWithNil(function: self.interactor.getContactOptions)
*/
let (configsResult, optionsResult, updateStateResult, contactsResult)
= await (configs, options, updateState, contacts)
// you can inspect each result here if you'd like
self.goToNextPage()
}
The idea here is that you get a type that can contain both the response and error at the point of async let, rather than catching the error later.

Swift: Have a timeout for async/await function

Is there a way to attach a timeout to stop an async function if it takes too long?
Here's a simplified version of my code:
func search() async -> ResultEnum {
// Call multiple Apis one after the other
}
Task.init {
let searchResult = await search()
switch searchResult {
// Handle all result scenarios
}
}
I would like to have a deadline for the search() async function to provide a result, otherwise it should terminate and return ResultEnum.timeout.
Thank you Rob for your comments, and for the link you provided.
I had to make some changes though, For some reason the initial task fetchTask kept going even after cancellation, until I added Task.checkCancellation() to it.
Here's what the code looks like now, if anyone is facing a similar issue:
func search() async throws -> ResultEnum {
// This is the existing method as per my initial question.
// It calls multiple Apis one after the other, then returns a result.
}
// Added the below method to introduce a deadline for search()
func search(withTimeoutSecs: Int) async {
let fetchTask = Task {
let taskResult = try await search()
try Task.checkCancellation()
// without the above line, search() kept going until server responded long after deadline.
return taskResult
}
let timeoutTask = Task {
try await Task.sleep(nanoseconds: UInt64(withTimeoutSecs) * NSEC_PER_SEC)
fetchTask.cancel()
}
do {
let result = try await fetchTask.value
timeoutTask.cancel()
return result
} catch {
return ResultEnum.failed(NetworkError.timeout)
}
}
// Call site: Using the function (withTimeout:) instead of ()
Task.init {
let searchResult = await search(withTimeoutSecs: 6)
switch searchResult {
// Handle all result scenarios
}
}

Run function after two functions has ran

So let's say I have these three functions:
func func_1() {
Task { #MainActor in
let state = try await api.get1State(v!)
print("cState func_1: \(state!)")
}
}
func func_2() {
Task { #MainActor in
let state = try await api.get2State(v!)
print("cState func_2: \(state!)")
}
}
func func_3() {
Task { #MainActor in
let state = try await api.get3State(v!)
print("cState func_3: \(state!)")
}
}
Since these function get info from api, it might take a few seconds.
How can I run func_3, after both func_1 and func_2 is done running?
I would advise avoiding Task (which opts out of structured concurrency, and loses all the benefits that entails) unless you absolutely have to. E.g., I generally try to limit Task to those cases where I are going from a non-asynchronous context to an asynchronous one. Where possible, I try to stay within structured concurrency.
As The Swift Programming Language: Concurrency says:
Tasks are arranged in a hierarchy. Each task in a task group has the same parent task, and each task can have child tasks. Because of the explicit relationship between tasks and task groups, this approach is called structured concurrency. Although you take on some of the responsibility for correctness, the explicit parent-child relationships between tasks lets Swift handle some behaviors like propagating cancellation for you, and lets Swift detect some errors at compile time.
And I would avoid creating functions (func_1, func_2, and func_3) that fetch a value and throw it away. You would presumably return the values.
If func_1 and func_2 return different types, you could use async let. E.g., if you're not running func_3 until the first two are done, perhaps it uses those values as inputs:
func runAll() async throws {
async let foo = try await func_1()
async let bar = try await func_2()
let baz = try await func_3(foo: foo, bar: bar)
}
func func_1() async throws -> Foo {
let foo = try await api.get1State(v!)
print("cState func_1: \(foo)")
return foo
}
func func_2() async throws -> Bar {
let bar = try await api.get2State(v!)
print("cState func_2: \(bar)")
return bar
}
func func_3(foo: Foo, bar: Bar) async throws -> Baz {
let baz = try await api.get3State(foo, bar)
print("cState func_3: \(baz)")
return baz
}
Representing that visually using “Points of Interest” tool in Instruments:
The other pattern, if func_1 and func_2 return the same type, is to use a task group:
func runAll() async throws {
let results = try await withThrowingTaskGroup(of: Foo.self) { group in
group.addTask { try await func_1() }
group.addTask { try await func_2() }
return try await group.reduce(into: [Foo]()) { $0.append($1) } // note, this will be in the order that they complete; we often use a dictionary instead
}
let baz = try await func_3(results)
}
func func_1() async throws -> Foo { ... }
func func_2() async throws -> Foo { ... }
func func_3(_ values: [Foo]) async throws -> Baz { ... }
There are lots of permutations of the pattern, so do not get lost in the details here. The basic idea is that (a) you want to stay within structured concurrency; and (b) use async let or TaskGroup for those tasks you want to run in parallel.
I hate to mention it, but for the sake of completeness, you can used Task and unstructured concurrency. From the same document I referenced above:
Unstructured Concurrency
In addition to the structured approaches to concurrency described in the previous sections, Swift also supports unstructured concurrency. Unlike tasks that are part of a task group, an unstructured task doesn’t have a parent task. You have complete flexibility to manage unstructured tasks in whatever way your program needs, but you’re also completely responsible for their correctness.
I would avoid this because you need to handle/capture the errors manually and is somewhat brittle, but you can return the Task objects, and await their respective result:
func func_1() -> Task<(), Error> {
Task { #MainActor [v] in
let state = try await api.get1State(v!)
print("cState func_1: \(state)")
}
}
func func_2() -> Task<(), Error> {
Task { #MainActor [v] in
let state = try await api.get2State(v!)
print("cState func_2: \(state)")
}
}
func func_3() -> Task<(), Error> {
Task { #MainActor [v] in
let state = try await api.get3State(v!)
print("cState func_3: \(state)")
}
}
func runAll() async throws {
let task1 = func_1()
let task2 = func_2()
let _ = await task1.result
let _ = await task2.result
let _ = await func_3().result
}
Note, I did not just await func_1().result directly, because you want the first two tasks to run concurrently. So launch those two tasks, save the Task objects, and then await their respective result before launching the third task.
But, again, your future self will probably thank you if you remain within the realm of structured concurrency.

How to resume a continuation ensuring that the result is delivered on the MainActor?

I have a continuation:
func a() async -> Int {
await withCheckedContinuation { continuation in
continuation.resume(returning: 3)
}
}
I would like all callers of this function to receive the result on the MainActor. I wouldn't like the caller to have to explicitly specify this rescheduling. I don't want this:
func c() async {
let three = await a()
await MainActor.run {
b(three)
}
}
What I instead want is for the entire code after returning to be performed on the MainThread until the next suspension point, something like this:
func c1() async {
let three = await a()
b(three) // Guaranteed main thread, although nothing speaks of it here
}
In a way, I want a to declare that I return only on main actor!, like this:
func a() #MainActor async -> Int {
await withCheckedContinuation { continuation in
continuation.resume(returning: 3)
}
}
Is there any way to even do this?
UPDATE:
Both commenters have suggested that I annotate the enclosing functions c and c1 with #MainActor.
#MainActor
func c() async {
let three = await a()
await MainActor.run {
b(three)
}
}
This doesn't do it like I need it. It says:
every time I await somebody, they must return on the main thread
But what I need instead is this:
every time somebody awaits me, they must get my result on the main thread
No, there is no way to do this.
If you await some function, you can decide on which thread will it return.
But being an await-able function, you can not make sure that your result will be delivered to the caller on a particular and/or main thread.

Swift async method call for a command line app

I'm trying to reuse some async marked code that works great in a SwiftUI application in a simple Swift-Command line tool.
Lets assume for simplicity that I'd like to reuse a function
func fetchData(base : String) async throws -> SomeDate
{
let request = createURLRequest(forBase: base)
let (data, response) = try await URLSession.shared.data(for: request)
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
throw FetchError.urlResponse
}
let returnData = try! JSONDecoder().decode(SomeData.self, from: data)
return returnData
}
in my command line application.
A call like
let allInfo = try clerk.fetchData("base")
in my "main-function" gives the error message 'async' call in a function that does not support concurrency.
What is the correct way to handle this case.
Thanks
Patrick
To call an async method the call must take place inside an async method or wrapped in a Task.
Further the method must be called wirh await
Task {
do {
let allInfo = try await clerk.fetchData("base")
} catch {
print(error)
}
}
You can make the entry point of the CLI async with this syntax
#main
struct CLI {
static func main() async throws {
let args = CommandLine.arguments
...
}
The name of the struct is arbitrary.
If you are using Argument Parser framework then from version 1.0 it supports async context. You have to make your struct conforms to protocol AsyncParsableCommand. It creates context in which async function can be run safely.