/*:#localized(key: "DefiningAndCallingAnAsyncFunction")
 # Defining and calling an async function

 An **async function** is a function that's allowed to pause partway through
 and resume later. You mark it with `async` in its signature, and you call it
 with the `await` keyword:
 */
//#-editable-code
import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

func brewEspresso() async -> String {
    try? await Task.sleep(for: .seconds(1))   // the machine pulls a shot
    return "☕️ Espresso"
}

Task {
    let cup = await brewEspresso()
    print("Served: \(cup)")
    PlaygroundPage.current.finishExecution()
}

print("Order taken, the counter is still open")
//#-end-editable-code
/*:#localized(key: "DefiningAndCallingAnAsyncFunction-2")
 Two keywords are doing all the work here:

 * **`async`** on `brewEspresso()` announces "this function may need to wait."
 Calling it isn't like calling a normal function that runs straight through.
 * **`await`** at the call site marks the spot where waiting might happen. You
 can read it as "pause here if needed, and pick up on the next line once the
 result is ready."

 We simulate the slow shot with `Task.sleep(for:)`, which is the async way to
 wait a while. (It *is* throwing, it can be cancelled, so here we ignore that
 with `try?`; you'll handle cancellation properly in the chapter [Tasks and Cancellation](Tasks%20and%20Cancellation.playgroundchapter/Overview).)

 **Watch it run:** `Order taken, the counter is still open` prints **first**,
 then about a second later you see `Served: ☕️ Espresso`. The `await` didn't
 stop the rest of the page; the last line ran while the espresso was still
 brewing. That gap is the whole point of this chapter.

 * callout(Try it): Change the espresso delay from `.seconds(1)` to
 `.seconds(3)`, does `Order taken, the counter is still open` still print
 first?

 [Previous](@previous)  |  page 2 of 8  |  [Next: What Await Actually Means](@next)
 */
