简体   繁体   English

Swift:如何将“完成”包装到异步/等待中?

[英]Swift: how to wrap `completion` into an async/await?

I have a callback based API.我有一个基于回调的 API。

func start(_ completion: @escaping () -> Void)

I'd like to write an async/await wrapper on top of that API, deferring the implementation to original callback based API.我想在该 API 之上编写一个 async/await 包装器,将实现推迟到基于原始回调的 API。

func start() async {
    let task = Task()
    start { 
        task.fulfill()
    }
    
    return await task
}

Obviously, this code doesn't connect - it's not real, there is no method fulfill on Task .显然,这段代码没有连接——它不是真实的, Task上没有fulfill方法。

Question: is there a way to use unstructured concurrency in Swift so that it would help me achieve this?问题:有没有办法在 Swift 中使用非结构化并发来帮助我实现这一目标?

You are looking for continuations .您正在寻找延续

Here is how to use it in your example:以下是如何在您的示例中使用它:

func start() async {
    await withCheckedContinuation { continuation in
        start(continuation.resume)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM