Created
February 27, 2015 13:46
-
-
Save r-wheeler/b2e8fe24055d9f63d6be to your computer and use it in GitHub Desktop.
Futures.scala
This file contains hidden or 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
//Here is the example Scala code, it assumes a function called fetch which when given a URL will return a Future. | |
def getThumbnail(url: String): Future[Webpage] = { | |
val promise = new Promise[Webpage] | |
fetch(url) onSuccess { page => | |
fetch(page.imageLinks(0)) onSuccess { p => | |
promise.setValue(p) | |
} onFailure { exc => | |
promise.setException(exc) | |
} | |
} onFailure { exc => | |
promise.setException(exc) | |
} | |
promise | |
} | |
// Scala Futures have a method called flatMap, which takes a function that given value will return another Future. Here is an | |
//example of how the getThumbnail method can be simplified by using it. | |
def getThumbnail(url: String): Future[Webpage] = | |
fetch(url) flatMap { page => | |
fetch(page.imageLinks(0)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment