Name: purescript-aff
Owner: SlamData, Inc.
Description: An asynchronous effect monad for PureScript
Created: 2015-02-27 21:08:39.0
Updated: 2018-05-20 11:02:43.0
Pushed: 2018-05-12 18:16:46.0
Homepage: null
Size: 385
Language: PureScript
GitHub Committers
User | Most Recent Commit | # Commits |
---|
Other Committers
User | Most Recent Commit | # Commits |
---|
An asynchronous effect monad and threading model for PureScript.
= launchAff do
sponse <- Ajax.get "http://foo.bar"
g response.body
r install purescript-aff
An example of Aff
is shown below:
teBlankLines path = do
ntents <- loadFile path
t contents' = S.join "\n" $ A.filter (\a -> S.length a > 0) (S.split "\n" contents)
veFile path contents'
This looks like ordinary, synchronous, imperative code, but actually operates asynchronously without any callbacks. Error handling is baked in so you only deal with it when you want to.
The library contains instances for Semigroup
, Monoid
, Apply
,
Applicative
, Bind
, Monad
, Alt
, Plus
, MonadEffect
, MonadError
, and
Parallel
. These instances allow you to compose asynchronous code as easily
as Effect
, as well as interop with existing Effect
code.
Hopefully, you're using libraries that already use the Aff
type, so you
don't even have to think about callbacks!
If you're building your own library, then you can make an Aff
from
low-level Effect
callbacks with makeAff
.
Aff :: forall a. ((Either Error a -> Effect Unit) -> Effect Canceler) -> Aff a
This function expects you to provide a handler, which should call the supplied callback with the result of the asynchronous computation.
You should also return Canceler
, which is just a cleanup effect. Since
Aff
threads may be killed, all asynchronous operations should provide a
mechanism for unscheduling it.
Effect.Aff.Compat
provides functions for easily binding FFI
definitions:
rts._ajaxGet = function (request) { // accepts a request
turn function (onError, onSuccess) { // and callbacks
var req = doNativeRequest(request, function (err, response) { // make the request
if (err != null) {
onError(err); // invoke the error callback in case of an error
} else {
onSuccess(response); // invoke the success callback with the reponse
}
});
// Return a canceler, which is just another Aff effect.
return function (cancelError, cancelerError, cancelerSuccess) {
req.cancel(); // cancel the request
cancelerSuccess(); // invoke the success callback for the canceler
};
urescript
ign import _ajaxGet :: Request -> EffectFnAff Response
We can wrap this into an asynchronous computation like so:
Get :: Request -> Aff Response
Get = fromEffectFnAff <<< _ajaxGet
This eliminates callback hell and allows us to write code simply using do
notation:
ple = do
sponse <- ajaxGet req
g response.body
All purely synchronous computations (Effect
) can be lifted to asynchronous
computations with liftEffect
defined in Effect.Class
.
Effect $ log "Hello world!"
This lets you write your whole program in Aff
, and still call out to
synchronous code.
Aff
has error handling baked in, so ordinarily you don't have to worry
about it.
When you need to deal with failure, you have a few options.
Because Aff
has an Alt
instance, you may also use the operator <|>
to
provide an alternative computation in the event of failure:
ple = do
sult <- Ajax.get "http://foo.com" <|> Ajax.get "http://bar.com"
re result
Aff
has a MonadError
instance, which comes with two functions:
catchError
, and throwError
.
These are defined in purescript-transformers. Here's an example of how you can use them:
ple = do
sp <- Ajax.get "http://foo.com" `catchError` \_ -> pure defaultResponse
en (resp.statusCode /= 200) do
throwError myErr
re resp.body
Aff
threads can be cancelled, but sometimes we need to guarantee an action
gets run even in the presence of exceptions or cancellation. Use bracket
to
acquire resources and clean them up.
ple =
acket
(openFile myFile)
(\file -> closeFile file)
(\file -> appendFile "hello" file)
In this case, closeFile
will always be called regardless of exceptions once
openFile
completes.
Using forkAff
, you can “fork” an asynchronous computation, which means
that its activities will not block the current thread of execution:
Aff myAff
Because Javascript is single-threaded, forking does not actually cause the computation to be run in a separate thread. Forking just allows the subsequent actions to execute without waiting for the forked computation to complete.
Forking returns a Fiber a
, representing the deferred computation. You can
kill a Fiber
with killFiber
, which will run any cancelers and cleanup, and
you can observe a Fiber
's final value with joinFiber
. If a Fiber
threw
an exception, it will be rethrown upon joining.
ple = do
ber <- forkAff myAff
llFiber (error "Just had to cancel") fiber
sult <- try (joinFiber fiber)
isLeft result
then (log "Canceled")
else (log "Not Canceled")
The Parallel
instance for Aff
makes writing parallel computations a breeze.
Using parallel
from Control.Parallel
will turn a regular Aff
into
ParAff
. ParAff
has an Applicative
instance which will run effects in
parallel, and an Alternative
instance which will race effects, returning the
one which completes first (canceling the others). To get an Aff
back, just
run it with sequential
.
ake two requests in parallel
ple =
quential $
Tuple <$> parallel (Ajax.get "https://foo.com")
<*> parallel (Ajax.get "https://bar.com")
urescript
ake a request with a 3 second timeout
ple =
quential $ oneOf
[ parallel (Just <$> Ajax.get "https://foo.com")
, parallel (Nothing <$ delay (Milliseconds 3000.0))
]
urescript
ows =
"Stargate_SG-1"
"Battlestar_Galactica"
"Farscape"
age page =
ax.get $ "https://wikipedia.org/wiki/" <> page
et all pages in parallel
ages = parTraverse getPage tvShows
et the page that loads the fastest
estPage = parOneOfMap getPage tvShows
API documentation is published on Pursuit.