Skip to content

Instantly share code, notes, and snippets.

@danveloper
Created May 20, 2016 13:18
Show Gist options
  • Save danveloper/67061809e12afd8cfbb23689331d684c to your computer and use it in GitHub Desktop.
Save danveloper/67061809e12afd8cfbb23689331d684c to your computer and use it in GitHub Desktop.
/**
* The `Promise#map` method is used to retrieve
* a value asynchronously (via a `Promise`) and
* transform it synchronous to a new value.
*/
class MappingSpec extends Specification {
@AutoCleanup
ExecHarness harness = ExecHarness.harness()
Promise<Integer> getInteger() {
Promise.sync {
return 1
}
}
Promise<Integer> makeNumber() {
getInteger().map { i ->
i + 2
}
}
void "should map value of promise to new value"() {
when:
def result = harness.yieldSingle {
makeNumber()
}.value
then:
result == 3
}
}
/**
* The `Promise#flatMap` method is used to retrieve
* a value asynchronously (via a `Promise`) and
* transform it asynchronously (via another `Promise`)
* to a new value
*
*/
class FlatMappingSpec extends Specification {
@AutoCleanup
ExecHarness harness = ExecHarness.harness()
Promise<Integer> getFirstInteger() {
Promise.sync {
return 1
}
}
Promise<Integer> getSecondNumber() {
Promise.sync {
return 2
}
}
Promise<Integer> makeNumber() {
getFirstInteger().flatMap { i ->
getSecondInteger().map { x ->
return i + x
}
}
}
void "should map value of two promises to new value"() {
when:
def result = harness.yieldSingle {
makeNumber()
}.value
then:
result == 3
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment