Skip to content

Instantly share code, notes, and snippets.

@r-wheeler
Created February 27, 2015 13:46
Show Gist options
  • Save r-wheeler/b2e8fe24055d9f63d6be to your computer and use it in GitHub Desktop.
Save r-wheeler/b2e8fe24055d9f63d6be to your computer and use it in GitHub Desktop.
Futures.scala
//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