Skip to content

Instantly share code, notes, and snippets.

@jjv360
Last active March 16, 2020 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjv360/a29896e99741eb1af3e9b90fbe294e88 to your computer and use it in GitHub Desktop.
Save jjv360/a29896e99741eb1af3e9b90fbe294e88 to your computer and use it in GitHub Desktop.
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