2013-02-07 51 views
3

我下面的dispatch文檔的第一個例子 -斯卡拉 - 派遣例如不工作

val svc = url("http://api.hostip.info/country.php") 
    val country = Http(svc OK as.String) 
    for (c <- country) 
     println(c) 

我沒有得到任何輸出打印。當我改變它到下面,使阻塞呼叫,然後我得到輸出。

val res = country() 
println(res) 

需要此幫助。

全部程序 -

import dispatch._ 
object DispatchTest { 

    def main(args: Array[String]) { 
    val svc = url("http://api.hostip.info/country.php") 
    val country = Http(svc OK as.String) 
    for (c <- country) 
     println(c) 
    } 
} 
+0

我不認爲是封鎖..水庫仍然是一個未來沒有?試試println(res.get) – twillouer

+0

對我來說,它的工作原理是......並且它應該是這樣的,因爲'for'理解將'println'命令包裝在'Promise'對象中,所以它只會在' c'值可用 –

+0

您使用的是什麼版本的dispatch?你可以展示你的build.sbt或其他? –

回答

6

嗯,不知道這裏,但也許問題是,你的主線程完成得如此之快,後臺線程(其中調度工作異步)沒有時間採取行動?

要檢查這一點,你可以嘗試插入延遲:

for (c <- country) // Here we spawn a background thread! 
    println(c) 

Thread.sleep(500) // So let's wait half a second for it to work 

當然,在實際的程序,你應該永遠需要做到這一點。

延遲的另一種選擇是簡單地在主結束時的readLine()

+0

你也可以檢查你的代碼是否工作,當你把它粘貼到sbt-console中 –

+0

是的。當我添加延遲時,我會得到輸出。謝謝! – Shwetanka

+0

如果連接速度很慢,您可能需要延長延遲時間。 – AnonGeek

0

它在這裏工作:

scala> import dispatch._ 
import dispatch._ 

scala> val svc = url("http://api.hostip.info/country.php") 
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". 
SLF4J: Defaulting to no-operation (NOP) logger implementation 
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. 
svc: com.ning.http.client.RequestBuilder = [email protected] 

scala> val country = Http(svc OK as.String) 
country: dispatch.Promise[String] = Promise(-incomplete-) 

scala> for (c <- country) 
    | println(c) 

scala> BR 

注意BR該提示後出現。

你確定這個國家沒有印在某個地方,但你沒有注意到,因爲它與其他輸出混淆了嗎?

+0

我將它作爲主要功能運行。我更新了我的問題。 – Shwetanka