定义和调用异步函数

<aside> 🍼 当一个函数既包含异步调用,又可能抛出异常时,async 要写在 throws 前。

</aside>

可以调用异步方法或函数的场景:

<aside> 🍭 1. 异步函数、方法或变量内部的代码; 2. 静态函数 main() 中被标记为 @main 的结构体、类或枚举中的代码; 3. 游离的子任务中的代码。

</aside>

异步序列

import Foundation

let handle = FileHandle.standardInput
for try await line in handle.bytes.lines {
    print(line)
}

并行调用异步方法

// 每一行对 `downloadPhoto` 方法的调用都需要等上一行完成才能开始
let firstPhoto = await downloadPhoto(named: photoNames[0])
let secondPhoto = await downloadPhoto(named: photoNames[1])
let thirdPhoto = await downloadPhoto(named: photoNames[2])

let photos = [firstPhoto, secondPhoto, thirdPhoto]
show(photos)
// 三行为并行调用,最后再用 `await` 等待全部完成
async let firstPhoto = downloadPhoto(named: photoNames[0])
async let secondPhoto = downloadPhoto(named: photoNames[1])
async let thirdPhoto = downloadPhoto(named: photoNames[2])

let photos = await [firstPhoto, secondPhoto, thirdPhoto]
show(photos)

任务和任务组

Apple Developer Documentation

Apple Developer Documentation

await withTaskGroup(of: Data.self) { taskGroup in
    let photoNames = await listPhotos(inGallery: "Summer Vacation")
    for name in photoNames {
        taskGroup.addTask { await downloadPhoto(named: name) }
    }
}

非结构化并发