<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)
await withTaskGroup(of: Data.self) { taskGroup in
let photoNames = await listPhotos(inGallery: "Summer Vacation")
for name in photoNames {
taskGroup.addTask { await downloadPhoto(named: name) }
}
}