Making several parallel async calls that might throw, will the rest run?

I've got some code that needs to make a handful of await calls of Void methods:

	public
	func
	idle(at inTemp: UInt16)
		async
		throws
	{
		await self.eurotherm.stopProgram()
		try await set(temperature: inTemp)
		try await set(inputSensor: .furnace)
		try await self.alicat1.set(flowRate: 0.0)
		try await self.alicat2.set(flowRate: 0.0)
	}

It’s possible for those to throw, but if one throws I want it to attempt the rest. I know with functions that return a value I can write async let foo =, but what do I do for Void functions? And even in the parallel case of functions that return values, will they all be guaranteed to run even if one should throw?

Is this where I need a task group, even though it's a static number of tasks?

1 Like

You could use try? to ignore any error that occurs, that way it would continue execution.

I am assuming running in parallel is not your requirement, if you want them to run in parallel then you could use withThrowingTaskGroup instead

Given below is an example:

func f1() async {
    
    try? await doSomething(number: -10)
    try? await doSomething(number: 20)
    try? await doSomething(number: -30)
    try? await doSomething(number: 40)
}

func doSomething(number: Int) async throws {
    if number >= 0 {
        print("number = \(number)")
    } else {
        throw NSError(domain: "some error", code: 11, userInfo: nil)
    }
}

Task {
    await f1()
}
1 Like

Well, that's so obvious I am now embarrassed. Thanks!

No worries, often happens with me as well, quite a lot of concepts for me to learn / understand, so sometimes I miss the obvious :)

1 Like