In the code below, “ALL tasks completed” is being printed before the 3 tasks are actually complete. How can I make sure to wait until they’re all finished before executing the MainActor code?
Task {
async let _ = func1()
async let _ = func2()
async let _ = func3()
await MainActor.run {
print("ALL tasks completed")
}
}
func func1() async {
try? await someOtherWork()
print("func1 complete")
}
func2 and func3 would be similar to func1.
2
You need to explicitly await
the function calls, like so:
Task {
async let f1: () = func1()
async let f2: () = func2()
async let f3: () = func3()
let _ = await (f1, f2, f3)
print("ALL tasks completed")
}
assuming you want all funcX
to run in parallel.
If it’s OK to simply run them in sequence, get rid of async let
and simply await func1()
etc.
1