@@ -13,6 +13,7 @@ It is expected that you know how React itself works.
1313- [ React Extensions] ( #react-extensions )
1414- [ Differences from React proper] ( #differences-from-react-proper )
1515- [ Using JS Components] ( #using-js-components )
16+ - [ Callbacks and Futures] ( #callbacks-and-futures )
1617- [ Gotchas] ( #gotchas )
1718
1819Setup
@@ -586,6 +587,48 @@ mountedComponent.foreach(c => // GOOD: call setState
586587 c.setState(SampleReactComponentState (c.state)(num2 = 1 )))
587588```
588589
590+ Callbacks and Futures
591+ =====================
592+
593+ There are a number of conversions available to convert between ` Callback ` and ` Future ` .
594+
595+ | Input | Method | Output |
596+ | -------------------------- | ---------------------- | ----------------------- |
597+ | ` CallbackTo[A] ` | ` cb.toFuture ` | ` Future[A] ` |
598+ | ` CallbackTo[Future[A]] ` | ` cb.toFlatFuture ` | ` Future[A] ` |
599+ | ` => Future[A] ` | ` CallbackTo(f) ` | ` CallbackTo[Future[A]] ` |
600+ | ` => Future[CallbackTo[A]] ` | ` Callback.future(f) ` | ` Callback ` |
601+ | ` => Future[CallbackTo[A]] ` | ` CallbackTo.future(f) ` | ` CallbackTo[Future[A]] ` |
602+
603+ ** NOTE:** It's important that when going from ` Future ` to ` Callback ` , you're aware of when the ` Future ` is instantiated.
604+
605+ ``` scala
606+ def queryServer : Future [Data ] = ???
607+
608+ def updateComponent : Future [Callback ] =
609+ queryServer.map($ setState _)
610+
611+ // This is GOOD because the callback wraps the updateComponent *function*, not an instance.
612+ Callback .future(updateComponent)
613+
614+ // This is BAD because the callback wraps a single instance of updateComponent.
615+ // 1) The server will be contacted immediately instead of when the callback executes.
616+ // 2) If the callback is execute more than once, the future and old result will be reused.
617+ val f = updateComponent
618+ Callback .future(f)
619+
620+ // This is GOOD too because the future is created inside the callback.
621+ Callback .future {
622+ val f = updateComponent
623+ f.onComplete(??? )
624+ f
625+ }
626+ ```
627+
628+ If you're looking for ways to block (eg. turning a ` Callback[Future[A]] ` into a ` Callback[A] ` ),
629+ it is not supported by Scala.JS (See [ #1996 ] ( https://github.com/scala-js/scala-js/issues/1996 ) ).
630+
631+
589632Gotchas
590633=======
591634
0 commit comments