Async/Await Syntax in Swift, Kotlin and JavaScript
Most modern languages support the ability for asynchronous function calls to be called from synchronous code blocks. This language feature is usually called async/await.
This post is a brief syntax scratchpad comparing async/await in different languages.
Swift
In Swift, an await-able async function is created by adding the async
keyword immediately following the function parameter list. Swift documents async/await in its concurrency documentation here.
func calculate(_ a: Int, _ b: Int) async -> Int {
try? await Task.sleep(for: .seconds(5))
return a + b
}
To call an async function in Swift, precede the function call invocation with the await
keyword.
By default, Swift will suspend the thread calling await, and resume the thread when the await function returns.
let r1 = await calculate(2, 3)
// wait for successIn to complete
let r2 = await calculate(5, 6)
// after 10 seconds r1 and r2 are calculated
To run two or more async
invocations in parallel, assign them to let
variables and await them as an array of function variables.
async let r1 = await calculate(2, 3)
async let r2 = await calculate(5, 6)
// trigger both invocations at the same time
let results = await [r1, r1]
// after 5 seconds r1 and r2 are calculated, and returned as [Int] array in results
Kotlin
Kotlin async/await is called suspend
functions, and is documented on the kotlinlang.org site here.
suspend fun add(a: Int, b: Int): Int {
delay(5000L)
return a + b
}
The default behavior is the same as Swift, where the current coroutine is suspended and then resumed after a suspend function returns. In Kotlin, the await
keyword is not used at the point where the function is invoked.
val r1 = calculate(2, 3)
// wait for successIn to complete
val r2 = calculate(5, 6)
// after 10 seconds r1 and r2 are calculated
To run the two suspend
functions concurrently, wrap the suspend function calls in an async
block.
val r1 = async { calculate(2, 3) }
// second call is made immediately
val r2 = async { calculate(5, 6) }
// after 5 seconds r1 and r2 are calculated
JavaScript
In JavaScript, an async function is created using the async
keyword as in Swift, but the keyword is positioned at the start of the function declaration like Kotlin. Documentation for JavaScript Promise/await can be found here.
async function add(a, b) {
await sleep(5000)
return a + b
}
As with Swift, the function is called with the await
keyword. Like both Swift and Kotlin, the default behavior when calling an async
function is to suspend the current thread and continue after the async
function returns.
const r1 = await calculate(2, 3)
// wait for successIn to complete
const r2 = await calculate(5, 6)
// after 10 seconds r1 and r2 are calculated
Calling multiple await
functions in parallel can be done using Promise.all
.
const [r1, r2] = await Promise.all([calculate(2, 3), calculate(5, 6)])
// After 5 seconds, r1 and r2 are calculated