Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Kotlin中,当使用Kovenant Promise.of(value)时,有时会泄漏异常_Kotlin_Kovenant - Fatal编程技术网

在Kotlin中,当使用Kovenant Promise.of(value)时,有时会泄漏异常

在Kotlin中,当使用Kovenant Promise.of(value)时,有时会泄漏异常,kotlin,kovenant,Kotlin,Kovenant,使用Kovenant,我有时会使用Promise.of(value)函数来创建一个同步结果,并将其包装为Promise。但有时会打这样的电话: Promise.of(callSomeCalculation())log.error(ex)}问题是您正在承诺链之外泄漏异常。想象一下这个代码: fun makeMyPromise(): Promise<Int, Exception> { val result: Int = callSomeCalculation() // <

使用Kovenant,我有时会使用
Promise.of(value)
函数来创建一个同步结果,并将其包装为Promise。但有时会打这样的电话:


Promise.of(callSomeCalculation())log.error(ex)}问题是您正在承诺链之外泄漏异常。想象一下这个代码:

fun makeMyPromise(): Promise<Int, Exception> {
    val result: Int = callSomeCalculation()  // <--- exception occurs here
    val deferred = deferred<Int, Exception>()
    deferred.resolve(result)
    return deferred.promise
}
将更加正确并捕获您的异常。它确保了承诺链不会泄露任何信息

所以回到您的原始代码,您的
callSomeCalculation()
发生在调用
Promise.of()
方法之前,它无法提供这种保护。这发生在科文南意识到你甚至在创造承诺之前。因此,您需要一个新的
Promise.of(lambda)
方法,该方法接受可以完全防止此类泄漏的代码块

下面是一个新的
Promise.of(lambda)
扩展函数:

fun <V> Promise.Companion.of(codeBlock: () -> V): Promise<V, Exception> {
    val deferred = deferred<V, Exception>()
    try {
        deferred.resolve(codeBlock())
    }
    catch (ex: Exception) {
        deferred.reject(ex)
    }
    return deferred.promise
}
fun Promise.Companion.of(代码块:()->V):Promise{
val deferred=deferred()
试一试{
deferred.resolve(代码块())
}
捕获(例如:异常){
延期。拒绝(ex)
}
延期退换货
}
将用作:

Promise.of { callSomeCalculation() }   <-- sometimes throws exception
  .then { ... }
  .then { ... }
  .fail { ex -> log.error(ex) }        <-- exception ALWAYS logged!

Promise.of{callSomeCalculation()}log.error(ex)}这似乎是使用
task
方法的替代方法:。你能解释一下什么时候应该用它来代替任务吗?同步(承诺)与异步(任务)分派代码,但确保计算值不会泄漏异常。另一件事是,我对建议的
Promise.of
重载感到担忧的是,现在它的行为是意外的,当一个人想要得到函数类型的Promise时,却得到了PromiseNT的名字,如果这是你的关注。我不想添加到科文特图书馆,在那里他将需要考虑这些选项。我建议一个模型,不泄漏例外,我见过开发商泄漏他们太多次。一个例子,包括使其可重用,有人将不得不选择最好的名字。IVATE助手类您可以考虑您的世界,在其中您需要命名的东西和什么功能,你可能有,如果这是Kovenant作为一个特色建议,他将不得不考虑整个世界。
Promise.of { callSomeCalculation() }   <-- sometimes throws exception
  .then { ... }
  .then { ... }
  .fail { ex -> log.error(ex) }        <-- exception ALWAYS logged!