如何将此代码转换为async await
?
func syncFunction() -> String {
let result: String = try myEventLoopFutureWithResult.wait()
return result
}
字符串
到目前为止,我已经尝试过这种方法,但我无法获得操作的结果,并且它不会阻塞(但我希望它阻塞):
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:我想通过阻塞并获取结果来调用sync函数中的async
函数。
1条答案
按热度按时间bgtovc5b1#
好的,这样做的用例是从Vapor
Command
调用一个CMAC函数,但是最好使用AsyncCommand
,这样我就可以让所有东西都是CMAC了。