1+ module Web.Promise.Lazy where
2+
3+ import Prelude
4+
5+ import Data.Newtype (class Newtype )
6+ import Data.Traversable (traverse )
7+ import Effect (Effect )
8+ import Effect.Class (class MonadEffect )
9+ import Effect.Uncurried (mkEffectFn1 , runEffectFn1 , runEffectFn2 )
10+ import Web.Promise (Rejection )
11+ import Web.Promise.Internal as P
12+
13+ -- | A pure `Promise` that has not been executed yet. This type can be used
14+ -- | with `do` syntax.
15+ newtype LazyPromise a = LazyPromise (Effect (P.Promise a ))
16+
17+ derive instance newtypeLazyPromise :: Newtype (LazyPromise a ) _
18+
19+ instance functorLazyPromise :: Functor LazyPromise where
20+ map = liftM1
21+
22+ instance applyLazyPromise :: Apply LazyPromise where
23+ apply = ap
24+
25+ instance applicativeLazyPromise :: Applicative LazyPromise where
26+ pure = LazyPromise <<< pure <<< P .resolve
27+
28+ instance bindLazyPromise :: Bind LazyPromise where
29+ bind (LazyPromise p) k = LazyPromise do
30+ p' <- p
31+ runEffectFn2 P .then_ (mkEffectFn1 \a -> let (LazyPromise b) = k a in b) p'
32+
33+ instance monadLazyPromise :: Monad LazyPromise
34+
35+ instance monadEffectLazyPromise :: MonadEffect LazyPromise where
36+ liftEffect = LazyPromise <<< map P .resolve
37+
38+ catch :: forall a b . (Rejection -> LazyPromise b ) -> LazyPromise a -> LazyPromise b
39+ catch k (LazyPromise p) = LazyPromise do
40+ p' <- p
41+ runEffectFn2 P .catch (mkEffectFn1 \a -> let (LazyPromise b) = k a in b) p'
42+
43+ finally :: forall a . LazyPromise Unit -> LazyPromise a -> LazyPromise a
44+ finally (LazyPromise p1) (LazyPromise p2) = LazyPromise do
45+ p2' <- p2
46+ runEffectFn2 P .finally p1 p2'
47+
48+ all :: forall a . Array (LazyPromise a ) -> LazyPromise (Array a )
49+ all as = LazyPromise do
50+ as' <- traverse (\(LazyPromise a) -> a) as
51+ runEffectFn1 P .all as'
52+
53+ race :: forall a . Array (LazyPromise a ) -> LazyPromise a
54+ race as = LazyPromise do
55+ as' <- traverse (\(LazyPromise a) -> a) as
56+ runEffectFn1 P .race as'
0 commit comments