You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift封装带Result的回调为async/await时遇抛出函数类型转换错误

解决async/await封装completion函数时的错误问题

你遇到的错误是因为completion回调闭包本身不允许抛出错误,你在case .failure分支里直接throw error,导致闭包类型变成了throwing函数,但silentRefresh期望的是一个non-throwing的回调,所以类型不匹配。

在Swift的async/await封装中,不能直接在continuation的闭包里throw错误,而是要通过continuation.resume(throwing:)方法来传递错误,这是将completion风格的错误转换为async throws的标准方式。

调整后的代码如下:

func silentRefreshAsync(msalApplication: MSALPublicClientApplication) async throws -> RefreshedToken? {
    await withCheckedThrowingContinuation { continuation in
        silentRefresh(msalApplication: msalApplication) { result in
            switch result {
            case .failure(let error):
                print("\(error)")
                // 通过continuation传递错误,而不是直接throw
                continuation.resume(throwing: error)
            case .success(let token):
                continuation.resume(returning: token)
            }
        }
    }
}

关键调整点:

  • 将withCheckedContinuation替换为withCheckedThrowingContinuation:这个函数专门用于支持抛出错误的async函数封装
  • 把throw error改成continuation.resume(throwing: error):通过continuation把错误传递出去,让async函数能捕获并抛出这个错误

这样调整后,你的async函数就可以正确处理原completion中的Result错误,调用时只需要用try await即可捕获错误。

内容的提问来源于stack exchange,提问作者lcj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 08:35:24