swift 在sync函数中获取restart函数的结果

klh5stk1  于 4个月前  发布在  Swift
关注(0)|答案(1)|浏览(45)

如何将此代码转换为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函数。

bgtovc5b

bgtovc5b1#

好的,这样做的用例是从Vapor Command调用一个CMAC函数,但是最好使用AsyncCommand,这样我就可以让所有东西都是CMAC了。

相关问题