赞
踩
async-await 是在Swift 5.5 中的结构化并发变化的一部分,在swift中它主要用于允许多段代码同时运行。
async明确表明了一个方法执行异步操作,如下:
//定义了一个异步方法并且可以抛出异常
func fetchResult(_ value1: Int, _ value2: Int) async throws -> Int {
}
//async方法取代了以往我们使用的完成回调方法
func fetchResult(_ value1: Int, _ value2: Int, completion: (Result<Int, Error>) -> Void) {
}
await 是用于调用异步方法的关键字。await 跟async是一个组合,await始终等待async的回调。如下:
do {
let ret = try await fetchResult(5, 6)
print("Fetched result: \(ret).")
} catch {
print("Fetched err: \(error).")
}
当然,直接使用也许会遇到这种错误 ‘async’ call in a function that does not support concurrency
这时可以使用
func useAsyneAwait() async {
do {
let ret = try await fetchResult(5, 6)
print("Fetched result: \(ret).")
} catch {
print("Fetched err: \(error).")
}
}
或者使用Task.init 从一个支持并发的新任务中调用异步方法
func useAsyneAwait() {
Task {
do {
let ret = try await fetchResult(5, 6)
print("Fetched result: \(ret).")
} catch {
print("Fetched err: \(error).")
}
}
}
func fetchResult(_ value1: Int, _ value2: Int) async throws -> Int {
let ret = value1 + value2
//假设小于10就返回错误
guard ret > 10 else {
throw ResultError.failed
}
return ret
}
func fetchResult(_ value1: Int, _ value2: Int, completion: (Result<Int, Error>) -> Void) {
}
func useAsyneAwait() async {
do {
let ret = try await fetchResult(5, 6)
print("Fetched result: \(ret).")
} catch {
print("Fetched err: \(error).")
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。