You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让高阶函数返回其内部函数生成的结果?

解决方案

你的核心问题是当前doWork作为挂起函数,没有等待service.getString的回调执行就直接结束了,导致无法将回调内处理后的结果作为返回值。可以通过两种方式解决:

方式一:重构SomeService以符合协程规范(推荐)

既然getString本身是挂起函数,完全不需要用回调传递结果,直接返回String即可,代码逻辑会更简洁直观:

// 修改后的SomeService
class SomeService() {
    suspend fun getString(): String {
        delay(1000)
        return "work is done"
    }
}

// 修改后的doWork函数
suspend fun doWork(): DoWorkResult {
    fun onSomeString(someString: String): DoWorkResult {
        // 这里编写你的分析/处理逻辑
        return DoWorkResult(someString)
    }

    val someString = service.getString()
    return onSomeString(someString)
}

方式二:使用suspendCoroutine包装回调(无法修改Service时用)

如果没办法修改SomeService的代码,就用suspendCoroutine将基于回调的逻辑转换为挂起函数,让doWork等待回调触发后再返回结果:

suspend fun doWork(): DoWorkResult {
    fun onSomeString(someString: String): DoWorkResult {
        // 这里编写你的分析/处理逻辑
        return DoWorkResult(someString)
    }

    // 用suspendCoroutine挂起协程,直到回调触发并传递结果
    val someString = suspendCoroutine<String> { continuation ->
        service.getString { str ->
            continuation.resume(str)
        }
    }

    return onSomeString(someString)
}

原理说明

  • suspendCoroutine会暂停当前协程,直到我们调用continuation.resume()传递结果,这样doWork就会等待回调执行完成后,再继续处理并返回最终结果。
  • 如果需要处理协程取消逻辑,可以替换为suspendCancellableCoroutine,并通过invokeOnCancellation添加取消回调的逻辑。

内容的提问来源于stack exchange,提问作者Alexey Simchenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 15:10:39