[swift-evolution] Question about async await

Trevör ANNE DENISE trevor.annedenise at icloud.com
Sun Sep 17 05:51:58 CDT 2017


Hello everyone,

I have a few questions about async await in Swift.

Say that you have :

func foo() async {
	print("Hey")
	await bar()
	print("How are you ?")
}

First of all, am I right to say that :
1) If the bar function wasn't an async function, the thread would be blocked until bar returns, at this point print("How are you ?") would be executed and its only after that that the function calling foo() would get back "control"
2) Here (with async bar function), if bar() takes some time to execute, control is directly given back to the function calling foo() and, when bar() returns, print("How are you") will be executed.


Second question about why async/await are needed:
Since calling await must be done in an async function and since async function can only be called, then if we have :
func baz() async {
	await foo()
	print("Something else")
}

Does this mean that "print("Something else")" will actually be waiting for bar() (and foo()) to complete ?
If this is right, then, what surprises me a little is that in this specific case, if all functions hadn't been async, then the execution order would have exactly been the same, am I right ?
So why are async/await needed ? Except for clarity, what do they enable that wouldn't have been possible otherwise ? It's not exactly clear to me sometimes because even things like futures wouldn't seem impossible to build without async await.

About beginAsync, say that we do that on the main thread :
beginAsync {
	await someAsyncFunction()
}

Will someAsyncFunction() still be executed on the main thread if it was defined this way ?
func someAsyncFunction() async {
	for element in manyElements {
		doSomethingLong(element)
	}
}

In this case, when will the main "choose" to execute those instructions ?


Thank you !

Trevör





More information about the swift-evolution mailing list