当前位置:   article > 正文

Swift 中的 async await_async' call in a function that does not support co

async' call in a function that does not support concurrency

async await

async-await 是在Swift 5.5 中的结构化并发变化的一部分,在swift中它主要用于允许多段代码同时运行。

async

async明确表明了一个方法执行异步操作,如下:

//定义了一个异步方法并且可以抛出异常
func fetchResult(_ value1: Int, _ value2: Int) async throws -> Int {
    
}

//async方法取代了以往我们使用的完成回调方法
func fetchResult(_ value1: Int, _ value2: Int, completion: (Result<Int, Error>) -> Void) {
    
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

await

await 是用于调用异步方法的关键字。awaitasync是一个组合,await始终等待async的回调。如下:

do {
    let ret = try await fetchResult(5, 6)
    print("Fetched result: \(ret).")
} catch {
    print("Fetched err: \(error).")
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

当然,直接使用也许会遇到这种错误 ‘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).")
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

或者使用Task.init 从一个支持并发的新任务中调用异步方法

func useAsyneAwait() {
    Task {
        do {
            let ret = try await fetchResult(5, 6)
            print("Fetched result: \(ret).")
        } catch {
            print("Fetched err: \(error).")
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

最后组合

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).")
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/460726
推荐阅读
相关标签
  

闽ICP备14008679号