How do you convert a Future to a js.Promise in Scala.js? - scala.js

Since JavaScript doesn't have Futures (at least, not as a standard, as far as I know) but Futures are very prevalent in Scala code (including mine), it would be great to know how to convert from Future[A] to a js.Promise[A] when providing APIs in for consumption in JavaScript.
Is there an existing library function for this?

There is a library function for that.
import scala.scalajs.js.JSConverters._
val future: Future[A] = ...
val promise: js.Promise[A] = future.toJSPromise

Related

What are advantages of a Twitter Future over a Scala Future?

I know a lot of reasons for Scala Future to be better. Are there any reasons to use Twitter Future instead? Except the fact Finagle uses it.
Disclaimer: I worked at Twitter on the Future implementation. A little bit of context, we started our own implementation before Scala had a "good" implementation of Future.
Here're the features of Twitter's Future:
Some method names are different and Twitter's Future has some new helper methods in the companion.
e.g. Just one example: Future.join(f1, f2) can work on heterogeneous Future types.
Future.join(
Future.value(new Object), Future.value(1)
).map {
case (o: Object, i: Int) => println(o, i)
}
o and i keep their types, they're not casted into the least common supertype Any.
A chain of onSuccess is guaranteed to be executed in order:
e.g.:
f.onSuccess {
println(1) // #1
} onSuccess {
println(2) // #2
}
#1 is guaranteed to be executed before #2
The Threading model is a little bit different. There's no notion of ExecutionContext, the Thread that set the value in a Promise (Mutable implementation of a Future) is the one executing all the computations in the future graph.
e.g.:
val f1 = new Promise[Int]
f1.map(_ * 2).map(_ + 1)
f1.setValue(2) // <- this thread also executes *2 and +1
There's a notion of interruption/cancellation. With Scala's Futures, the information only flows in one direction, with Twitter's Future, you can notify a producer of some information (not necessarily a cancellation). In practice, it's used in Finagle to propagate the cancellation of a RPC. Because Finagle also propagates the cancellation across the network and because Twitter has a huge fan out of requests, this actually saves lots of work.
class MyMessage extends Exception
val p = new Promise[Int]
p.setInterruptHandler {
case ex: MyMessage => println("Receive MyMessage")
}
val f = p.map(_ + 1).map(_ * 2)
f.raise(new MyMessage) // print "Receive MyMessage"
Until recently, Twitter's Future were the only one to implement efficient tail recursion (i.e. you can have a recursive function that call itself without blowing up you call stack). It has been implemented in Scala 2.11+ (I believe).
As far as I can tell the main difference that could go in favor of using Twitter's Future is that it can be cancelled, unlike scala's Future.
Also, there used to be some support for tracing the call chains (as you probably know plain stack traces are close to being useless when using Futures). In other words, you could take a Future and tell what chain of map/flatMap produced it. But the idea has been abandoned if I understand correctly.

The "right" way to use write Slick 3.0 Scala queries in Play Framework

I'm using Slick 3.0 and (of course) almost all the examples out there cover Slick 2.x. Things have changed and frankly seem more complicated, not less.
Here's an example: I want to get an object (a GPPerson) by id. This is what I have right now, and it seems very verbose... more so than Slick 2.x:
def get(id: GPID): Option[GPPerson] = Await.result(
db.run(
people.filter(_.id === id).result), Duration.Inf
).headOption
In Slick 2.x things were easier because of the implicits, among other things. But the above seems to be the most concise expression I've come up with.
It also doesn't really address exception handling, which I would need to add.
I started to use Slick 3.0 in a new project a few months ago and I had the same questions. This is what I understood:
Slick 3.0 was designed for non-blocking asynchronous (reactive) applications. Obviously it means Akka + Play / Spray nowadays. In this world you mostly interact with Futures, that's why Slick's db.run returns Future. There is no point in using Await.result - if you need blocking calls it's better to return to 2.x.
But if you use reactive stack you'll get benefits immediately. For example, Spray is completely non-blocking library that works with Futures nicely using onComplete directive. You can call a method that returns Future with a result from Slick in a Spray route and then use that result together with onComplete. In this case the whole response-reply pipeline is non-blocking.
You also mentioned exception handling, so this is exactly how you do it - using Futures.
So based on my experience I would write your method in a following way:
def get(id: GPID): Future[Option[GPPerson]] = db.run(
people.filter(_.id === id).result.map(_.headOption)
)
and then work with a Future.
you can do this.
def syncResult[R](action:slick.dbio.DBIOAction[R, slick.dbio.NoStream, scala.Nothing]):R = {
import scala.concurrent.duration.Duration
val db = Database.forConfig("db")
try {
Await.result(db.run(action), Duration.Inf)
} finally db.close
}
def get(id: GPID): Option[GPPerson] = syncResult { people.filter(_.id === id).result.headOption }

A little help on understanding Scalaz Future and Task

I'm trying to understand the idea and purpose behind scalaz concurrent package, primarily Future and Task classes, but when using them in some application, it's now far from simple sequential analog, whereas scala.concurrent.Future, works more then better. Can any one share with his experience on writing concurrent/asynchronous application with scalaz, basically how to use it's async method correctly? As i understand from the sources async doesn't use a separate thread like the call to standard future, or fork/apply methods from scalaz works, so why it is called async then? Does it mean that in order to get real concurrency with scalaz i always have to call fork(now(...)) or apply?
I'm not a scalaz expert, but I'll try to help you a little bit. Let me try answer your questions one by one:
1) Can any one share with his experience on writing concurrent/asynchronous application with scalaz, basically how to use it's async method correctly?
Let's first take a look at async signature:
def async[A](listen: (A => Unit) => Unit): Future[A]
This could be a bit cryptic at first, so as always it's good idea to look at tests to understands possible use cases. In https://github.com/scalaz/scalaz/blob/scalaz-seven/tests/src/test/scala/scalaz/concurrent/FutureTest.scala
you can find the following code:
"when constructed from Future.async" ! prop{(n: Int) =>
def callback(call: Int => Unit): Unit = call(n)
Future.async(callback).run must_==
}
As we know from signature Future.async just construct new Future using function of signature (A => Unit) => Unit. What this really means is that Future.async takes as parameter function which for given callback makes all required computations and pass the result to that callback.
What is important to note it that Future.async does not run any computations on itself, it only prepare structure to run them later.
2) As i understand from the sources async doesn't use a separate thread like the call to standard future, or fork/apply methods from scalaz works, so why it is called async then?
You are correct. Only fork and apply seems to be running anything using threads, which is easy to notice looking at the signatures which contains implicit pool: ExecutorService. I cannot speak for the authors here, but I guess async is related to the callback. It means that rather than blocking on Future to get it result at the end you will use asynchronous callback.
3) Does it mean that in order to get real concurrency with scalaz i always have to call fork(now(...)) or apply?
From what I can say, yes. Just notice that when you are creating Future using syntax Future(x) you are using apply method here, so this is kind of default behavior (which is fine).
If you want to better understand design of Scalaz Futures I can recommend you reading "Functional Programming in Scala". I believe this book is written by main Scalaz contributors and chapter 7 discusses designing API for purely functional parallelism library. It's not exactly the same as Scalaz Future, but you can see many similarities.
You can also read wonderful Timothy Perrett blog post about Scalaz Task and Future which covers many not so obvious details.
async is used to adapt an async, callback-based API as a Future. It's called async because it's expected that it will be used with something that runs asynchronously, perhaps calling the callback from another thread somewhere further down the line. This is "real" concurrency, provided the API you're calling really uses it asynchronously (e.g. I use Future.async with the async parts of the AWS SDK like AmazonSimpleDBAsyncClient).
If you want "real" concurrency from the scalaz Task API directly you need to use things like fork or gatherUnordered, as many of the APIs default towards being safe/deterministic and restartable, with concurrency only when explicitly requested.
When composing Tasks with map and flatMap you can get a performance win by not using fork, see:
http://blog.higher-order.com/blog/2015/06/18/easy-performance-wins-with-scalaz/

Play Framework 2.2.0 [scala] - WebSocket.async vs WebSocket.using[T]

Can't seem to find any documentation on this but seeing some examples using WebSocket.async in actions as their return type and others using WebSocket.using[String].
Is there documentation anywhere as to when to use which? I understand that Websocket.using[String] is indicating that the types of messages coming in and out of this action are of type String. What exactly is the difference then using WebSocket.async? The main concern is when to use which and why.
Take a look at their respective signatures:
def using[A](f: RequestHeader => (Iteratee[A, _], Enumerator[A]))(implicit frameFormatter: FrameFormatter[A]): WebSocket[A]
def async[A](f: RequestHeader => Future[(Iteratee[A, _], Enumerator[A])])(implicit frameFormatter: FrameFormatter[A]): WebSocket[A]
A bit too much maybe, let's remove the return types and the implicit parameter lists as they're the same:
def using[A](f: RequestHeader => (Iteratee[A, _], Enumerator[A]))
def async[A](f: RequestHeader => Future[(Iteratee[A, _], Enumerator[A])])
The difference is easier to spot right now. The callback accepted by async returns a Future, whereas with using you can't. async is useful when you're working with asynchronous libraries, e.g. Akka, where sending a message to some actor yields a Future. using should be used with synchronous libraries. I hope it makes sense.

How do Akka and Async differ

I went to a very interesting lecture on Async (https://github.com/scala/async) a new library for Scala, what I am not sure about is how Akka and Async differ.
I am new to Scala so apologies if the answer is obvious.
Thanks.
Async simplifies asynchronous and concurrent programming. Async enables programming with non-blocking APIs in a familiar direct style. Direct-style code is as simple to write as blocking code, but it has all the advantages of efficient non-blocking code.
Out-of-the-box, Async makes programming with Scala's futures more convenient. In fact, by using Async with futures, your easy-to-read direct-style code is transformed to highly-efficient non-blocking code under the hood. Async can also be connected to other APIs (see below).
Akka provides a programming model and runtime to simplify concurrency, distribution, and fault tolerance. Async does not provide a runtime--it makes existing abstractions and their runtimes easier to use. However, Async and Akka can work together in several important ways:
Using Akka's "ask" pattern, sending a message using "?" returns a future. Async makes it easy to work with those futures.
Async can be connected to APIs other than Scala's Futures API. This opens up interesting ways to leverage Async to simplify programming with Akka actors. This is one area that we are going to explore in the near future at Typesafe.
Async is a replacement for Akka's dataflow API which is simpler and more robust. Async is simpler, because it does not introduce complex types stemming from the use of Scala's CPS plugin. Async is more robust, since it works well together with features like pattern matching and try-catch which are not fully supported by CPS/Akka's dataflow API. Moreover, it is clearly specified where Async cannot be used (await cannot occur inside closures, nested classes/traits/objects, or by-name arguments).
For more Async examples and documentation see my recent talk on Async and the documentation on the Async project website.
Async just adds helpfull API (and some other good internal things) for working with Future and has nothing to do with Actor model while Akka is a framework for creating massively-distributed with Actors. They have different use cases and have nothing in common. It more correctly to compare Async with Scala/Akka Futures API. I don't have much experience with Async, but the main point, is that you have two constructs async and await. Async marks a block of asynchronous code wich contains one or more await calls, which marks a point at which the computation will be suspended until the awaited Future is complete. Such API can be compared with a standart way of using map and flatmap .
Using standart API (for construct translates to combination of map and flatmap):
def slowCalcFuture: Future[Int] = ...
val future1 = slowCalcFuture
val future2 = slowCalcFuture
def combined: Future[Int] = for {
r1 <- future1
r2 <- future2
} yield r1 + r2
And Async:
def slowCalcFuture: Future[Int] = ...
def combined: Future[Int] = async {
val future1 = slowCalcFuture
val future2 = slowCalcFuture
await(future1) + await(future2)
}