async 和 await 异步函数

版本新特性 / Swift 5.5

// *** 以前 ***
func fetchUserOld(id: Int, completion: @escaping (User?, Error?) -> Void) { }
func fetchPostsOld(user: User, completion: @escaping ([Post]?, Error?) ->
                   Void) { }

fetchUserOld(id: 1) { user, error in
    guard let user = user else { return }          // 每个分支都必须记得
    fetchPostsOld(user: user) { posts, error in    // 调用 completion,
        guard let posts = posts else { return }    // 一旦漏掉一个 return,
        print(user, posts)                         // 界面就会永远卡住
    }
}

// *** 在 5.5 版本中 ***
func fetchUser(id: Int) async throws -> User { User() }
func fetchPosts(user: User) async throws -> [Post] { [] }

func load() async throws {
    let user = try await fetchUser(id: 1)
    let posts = try await fetchPosts(user: user)
    print(user, posts)
}

// await 标出函数可能被挂起的位置:线程被让出,
// 稍后再收回,代码仍然从上到下阅读。
// 错误走通常的 throws,结果走通常的 return