Как дождаться первого прибывшего результата в цепочке? - PullRequest
0 голосов
/ 13 октября 2018

Мы можем использовать Promise.race для ожидания первого полученного результата в цепочке thenable.Модуль Task , кажется, еще не поддерживает его, Task.sequence является только эквивалентом Promise.all .

Non-thenable Solution demo:

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"

1 Ответ

0 голосов
/ 13 октября 2018

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 =
    ...
...