如何将此代码转换为
async await
?
func syncFunction() -> String {
let result: String = try myEventLoopFutureWithResult.wait()
return result
}
``swift
I have tried this approach so far, but I cannot get the result of the operation and it doesn't block (but I want it to block):
```swift
func syncFunction() -> String {
Task {
try await myAsyncFunctionWithResult()
}
// missing return of async function ...
}
我发现了这个,它似乎阻塞了,但我无法得到我的
async
函数的结果:
func syncFunction() -> String {
let semaphore = DispatchSemaphore(value: 0)
Task(priority: priority) {
defer { semaphore.signal() }
return try await myAsyncFunctionWithResult()
}
semaphore.wait()
// missing return of async function ...
}
我发现的最后一种方法是这样的,我认为这种方法可行,但对于问题的简单程度来说有点复杂(我认为):
func syncFunction(eventLoop: EventLoop) -> String {
let promise = eventLoop.makePromise(of: String.self)
promise.completeWithTask {
try await myAsyncFunctionWithResult()
}
return try promise.futureResult.wait()
}
TLDR:我想通过阻塞并获取结果来调用同步函数中的
async
函数。
好的,执行此操作的用例是从 Vapor
Command
调用异步函数,但最好使用 AsyncCommand
来代替,这样我就可以使所有内容都异步