Kovenant utility: Recover block
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mypackage | |
import nl.komponents.kovenant.Promise | |
import nl.komponents.kovenant.deferred | |
import nl.komponents.kovenant.functional.bind | |
import nl.komponents.kovenant.task | |
import nl.komponents.kovenant.then | |
/** | |
* Utilities for recovering promises. | |
* Version: 1 | |
*/ | |
/** Recover using a block that returns the value directly */ | |
infix fun<V> Promise<V, Exception>.recover(block: (Exception) -> V) : Promise<V, Exception> { | |
// Create pending promise | |
val pending = deferred<V, Exception>() | |
// Run the promise | |
this success { | |
pending.resolve(it) | |
} fail { | |
// Failed! Run the recover function | |
val error = it | |
task {} then { block(error) } success { | |
pending.resolve(it) | |
} fail { | |
pending.reject(it) | |
} | |
} | |
// Done | |
return pending.promise | |
} | |
/** Recover using a block that returns a promise */ | |
infix fun<V> Promise<V, Exception>.recoverBind(block : (Exception) -> Promise<V, Exception>) : Promise<V, Exception> { | |
// Create pending promise | |
val pending = deferred<V, Exception>() | |
// Run the promise | |
this success { | |
pending.resolve(it) | |
} fail { | |
// Failed! Run the recover function | |
val error = it | |
task {} bind { block(error) } success { | |
pending.resolve(it) | |
} fail { | |
pending.reject(it) | |
} | |
} | |
// Done | |
return pending.promise | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment