krispo
krispo

Reputation: 526

how to use scala.concurrent.Future on the client side?

I need to make some consuming calculations on the server side (such as DB querying and data analisys). And the results need to be printed in browser. For these purpose I send Future result from server to client (to load web page immediately and gradually print future results from server). For example, on the server side

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
def futureResult = Future { 
  val cc = ConsumingCalculations();
  "some result" 
}

on the client side

@import scala.concurrent.ExecutionContext.Implicits.global
@main{
  @futureResult.onSuccess{ case res =>
    @println("This line is printed in console: "+res);
    <div>Any html code is NOT printed in browser</div>
  }
  Future result is NOT posted
}

In server consol we have: "This line is printed in console: some result"

But in the browser we have only: "Future result is NOT posted"

Play 2.1, scala 2.10 are currently used. What's may be wrong, are there any idea?

Upvotes: 0

Views: 502

Answers (1)

Julien Lafont
Julien Lafont

Reputation: 7877

A future cannot be sent on client side, it must be resolved on server side before displaying to the client.

The classic exemple is to map the result of your future in your controller

def myAction = Action {
    Async {
        futureResult.map(result =>
             Ok(views.html.myView(result))
        )
    }
}

And in your template, use the result, not the future.

Upvotes: 3

Related Questions