Created
July 27, 2021 03:50
-
-
Save purefunctor/e8bcca626854d43283d973fe74441fc1 to your computer and use it in GitHub Desktop.
PureScript `waitFor` combinator for Aff
This file contains 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
module Main where | |
import Prelude | |
import Data.Either (Either) | |
import Data.Int (round) | |
import Effect (Effect) | |
import Effect.Aff (Aff, Milliseconds(..), attempt, delay, error, forkAff, joinFiber, killFiber, launchAff_) | |
import Effect.Class (liftEffect) | |
import Effect.Class.Console (logShow) | |
import Effect.Exception (Error) | |
import Effect.Timer (clearTimeout, setTimeout) | |
waitFor :: forall r. Aff r -> Milliseconds -> Aff (Either Error r) | |
waitFor task (Milliseconds timeout_) = do | |
let timeout = round timeout_ | |
taskF <- forkAff task | |
timeoutId <- liftEffect $ | |
setTimeout timeout $ launchAff_ do | |
killFiber (error "waitFor: task timed out") taskF | |
result <- attempt $ joinFiber taskF | |
liftEffect $ clearTimeout timeoutId | |
pure result | |
slow :: Milliseconds -> Aff Int | |
slow timeout = do | |
delay timeout | |
pure 42 | |
main :: Effect Unit | |
main = launchAff_ do | |
result <- waitFor (slow (Milliseconds 500.0)) (Milliseconds 1000.0) | |
logShow result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment