2013-02-28 87 views
3

我有一個現有的Java類來處理數據。我如何從第一次承諾中使用ObjectNode,並在我的Scala異步操作中使用更多處理?玩2.1斯卡拉連鎖多期貨和承諾

public class JavaClass extends Controller { 
    public static Promise<ObjectNode> intensiveComputation(String imageId) { 
    } 
} 


def index = Action { 
    val futureInt = scala.concurrent.Future { JavaClass.intensiveComputation() } 
    Async { 
    futureInt.map(promise => 
     var objJs = promise.GetObjectNodeFromPromise() 
     (objJs \ Config.RESP_STATUS_PARAM).as[String] match { 
     // I WANT TO READ ObjectNode from promise and do more works here 
     } 
     Ok(Json.toJson(Map("status" -> "ok"))) 
    } 
} 

編輯1

我試圖與@hbf代碼,但是,我得到了編譯錯誤一個這條線。

[error] found : org.codehaus.jackson.node.ObjectNode => play.api.mvc.SimpleResult[play.api.libs.json.JsValue] 
[error] required: play.libs.F.Function[org.codehaus.jackson.node.ObjectNode,?] 
[error]     var result = futureObj map { objJs: ObjectNode => 

如果我從objJs中刪除了ObjectNode,我得到了這個錯誤。

[error] missing parameter type 
[error]     var result = futureObj map { objJs => 

新代碼

def index = Action { 
    val futureInt = JavaClass.intensiveComputation() 
    Async { 
    var result = futureObj map { objJs: ObjectNode => 
     Ok(Json.toJson(Map("status" -> "ok"))) 
    } 
    result 
} 

回答

4

我假設你遵循了Play documentation guide,對不對?首先,請注意,Play現在(從版本2.1開始)使用Scala期貨,並且由於此,命名法更改:您的方法intensiveComputation()返回(Scala)Future<ObjectNode>(在2.1之前版本中,這稱爲Promise<ObjectNode>)。

public class JavaClass extends Controller { 
    public static Future<ObjectNode> intensiveComputation(String imageId) { 
    /* ... */ 
    } 
} 

另外,還要注意的是,在Play documentation exampleintensiveComputation()返回值(即ObjectNode)直接,而你的版本會返回一個未來持有的值(即Future<ObjectNode>)。

其次,在您的futureInt.map中,封閉收到未來價值,而不是未來本身。因此,嘗試這樣的:。

def index = Action { 
    val futureInt = JavaClass.intensiveComputation() // I's already a future! 
    Async { 
    futureInt.map(objJs => // `objJs` is the result of `intensiveComputation` 
     // Extract from `objJs` whatever you need ... 
     // ... and make the `Ok` call here (and not outside) 
     Ok(Json.toJson(Map("status" -> "ok"))) 
    ) 
    } 
} 
+0

我試圖futureInt.map(objJs =>不過,我得到這個錯誤[錯誤]研究發現:org.codehaus.jackson.node.ObjectNode => play.api.mvc。 SimpleResult [play.api.libs.json.JsValue] [error] required:play.libs.F.Function [org.codehaus.jackson.node.ObjectNode ,?] – angelokh 2013-02-28 20:55:29

+0

還值得一提的是,只需通過Google搜索「Scala Async 「當你第一次打到Play 2.0的文檔時,你會得到這樣的結果,似乎Play在2.1(從Promise [T]到Future [T])中戲劇性地改變了異步編程的概念,所以這些文檔已經過時了。 – 2013-07-19 07:12:03