Skip to content

Instantly share code, notes, and snippets.

@jjv360
Last active March 16, 2020 23:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Kovenant utility: Recover block
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