如何在 thenable 链上等待第一个到达的结果?
How to wait for the first arrived result on the thenable chain?
我们可以使用Promise.race to wait for the first arrived result on the thenable
chain. The Task module doesn't seem to support it yet, Task.sequence is only the equivalent to Promise.all.
不可行解决方案演示:
import Process
import Task
init () =
( Nothing, Cmd.batch [ after 2 "2nd", after 1 "1st" ] )
after seconds name =
Process.sleep (1000 * seconds)
|> Task.map (always name)
|> Task.perform Done
type Msg
= Done String
update (Done name) model =
case model of
Nothing ->
( Debug.log name <| Just name, Cmd.none )
_ ->
( Debug.log name model, Cmd.none )
main =
Platform.worker
{ init = init
, update = update
, subscriptions = always Sub.none
}
运行 它,输出如预期:
1st: Just "1st"
2nd: Just "1st"
Promise.race
作为一个独立的函数需要维护本地状态以跟踪它是否已经被解析,正如您可能知道的那样,这在 Elm 中是不可能的。
但是您可以通过自己跟踪模型中的状态相对轻松地完成同样的事情。下面是一个使用 Maybe
来跟踪我们是否收到回复的示例:
type Thing =
...
getThings : String -> Task Never (List Thing)
getThings url =
...
type alias Model =
{ things : Maybe (List Thing) }
type Msg
= GotThings (List Thing)
init =
( { things = Nothing }
, Cmd.batch
[ Task.perform GotThings (getThings "https://a-server.com/things")
, Task.perform GotThings (getThings "https://a-different-server.com/things")
]
)
update msg model =
case msg of
GotThings things ->
case model.things of
Nothing ->
( { things = Just things }, Cmd.none )
Just _ ->
-- if we have already received the things, ignore any subsequent requests
( model, Cmd.none )
view model =
...
我们可以使用Promise.race to wait for the first arrived result on the thenable
chain. The Task module doesn't seem to support it yet, Task.sequence is only the equivalent to Promise.all.
不可行解决方案演示:
import Process
import Task
init () =
( Nothing, Cmd.batch [ after 2 "2nd", after 1 "1st" ] )
after seconds name =
Process.sleep (1000 * seconds)
|> Task.map (always name)
|> Task.perform Done
type Msg
= Done String
update (Done name) model =
case model of
Nothing ->
( Debug.log name <| Just name, Cmd.none )
_ ->
( Debug.log name model, Cmd.none )
main =
Platform.worker
{ init = init
, update = update
, subscriptions = always Sub.none
}
运行 它,输出如预期:
1st: Just "1st"
2nd: Just "1st"
Promise.race
作为一个独立的函数需要维护本地状态以跟踪它是否已经被解析,正如您可能知道的那样,这在 Elm 中是不可能的。
但是您可以通过自己跟踪模型中的状态相对轻松地完成同样的事情。下面是一个使用 Maybe
来跟踪我们是否收到回复的示例:
type Thing =
...
getThings : String -> Task Never (List Thing)
getThings url =
...
type alias Model =
{ things : Maybe (List Thing) }
type Msg
= GotThings (List Thing)
init =
( { things = Nothing }
, Cmd.batch
[ Task.perform GotThings (getThings "https://a-server.com/things")
, Task.perform GotThings (getThings "https://a-different-server.com/things")
]
)
update msg model =
case msg of
GotThings things ->
case model.things of
Nothing ->
( { things = Just things }, Cmd.none )
Just _ ->
-- if we have already received the things, ignore any subsequent requests
( model, Cmd.none )
view model =
...