Last active
August 29, 2015 14:17
-
-
Save sifue/292b9decd563fcdc42a8 to your computer and use it in GitHub Desktop.
JavaScriptのPromiseとScalaのPromiseは別物で、むしろScalaのFutureが似てる話 ref: http://qiita.com/sifue/items/4a003ce1edd519076546
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function doubleUp(value) { | |
| return value * 2; | |
| } | |
| function increment(value) { | |
| return value + 1; | |
| } | |
| function output(value) { | |
| console.log(value); | |
| } | |
| var promise = new Promise(function (resolve) { | |
| resolve(1); | |
| }); | |
| promise | |
| .then(increment) | |
| .then(doubleUp) | |
| .then(output) // 4が出力される | |
| .catch(function(error){ | |
| console.error(error); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import scala.concurrent.ExecutionContext.Implicits.global | |
| import scala.concurrent._ | |
| object MainFuture extends App { | |
| def double(value: Int): Int = value * 2 | |
| def increment(value: Int): Int = value + 1 | |
| def output(value: Int): Unit = Console.println(value) | |
| val future = Future {1} | |
| (for { | |
| i1 <- future | |
| i2 <- Future {increment(i1)} | |
| i3 <- Future {double(i2)} | |
| } yield output(i3)) // 4が出力される | |
| .onFailure { case t: Throwable => | |
| Console.println(t.getMessage) | |
| } | |
| Thread.sleep(1000) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import scala.concurrent.ExecutionContext.Implicits.global | |
| import scala.concurrent._ | |
| object MainPromise extends App { | |
| def output(value: Int): Unit = Console.println(value) | |
| val promise = Promise[Int] | |
| Future { | |
| promise.trySuccess(0) | |
| } | |
| Future { | |
| Thread.sleep(100) | |
| promise.trySuccess(1) | |
| } | |
| promise.future.map(output) // 先に終了する0が出力される | |
| Thread.sleep(1000) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment