如何将此代码转换为异步等待?
func syncFunction() -> String {
let result: String = try myEventLoopFutureWithResult.wait()
return result
}
到目前为止,我已经采用了这种方法,但是我无法获得操作的结果,并且它不会阻塞(但我希望它阻塞):
func syncFunction() -> String {
Task {
try await myAsyncFunctionWithResult()
}
// missing return of async function ...
}
我发现了这个,它似乎阻塞了,但我无法得到异步函数的结果:
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:我想通过阻塞并获取结果来调用同步函数中的异步函数
好吧,执行此操作的用例是从 Vapor
Command
调用异步函数,但最好使用 AsyncCommand
来代替,这样我就可以使所有内容都异步