How to execute multiple Http requests (Tasks) in bulk in Elm lang

I want to load a user profile before doing something on the page, but the entire user profile consists of different parts that are loaded with several HTTP requests.

While I load the user profile sequentially (one by one)

type alias CompanyInfo = 
  { name: String
  , address: ...
  , phone: String
  , ...
  }

type alias UserProfile = 
  { userName: String
  , companyInfo: CompanyInfo
  , ... 
  }

Cmd.batch
  [ loadUserName userId LoadUserNameFail LoadUserNameSuccess
  , loadCompanyInfo userId LoadCompanyInfoFail LoadCompanyInfoSuccess
  ...
  ]

But it is not very effective. Is there an easy way how to execute a bunch of Http requests and return only one full value?

Something like that

init = 
    (initialModel, loadUserProfile userId LoadUserProfileFail LoadUserProfileSuccess)

....
+4
source share
1 answer

You can achieve this using Task.map2:

Edit: Updated to Elm 0.18

Task.attempt LoadUserProfile <|
    Task.map2 (\userName companyInfo -> { userName = userName, companyInfo = companyInfo })
        (Http.get userNameGetUrl userDecoder |> Http.toTask)
        (Http.get companyInfoGetUrl companyInfoDecoder |> Http.toTask)

LoadUserName... LoadCompanyInfo... Msgs. Elm 0.18 Fail Succeed Msgs Task.attempt, Result Error Msg, LoadUserProfile :

type Msg
    = ...
    | LoadUserProfile (Result Http.Error UserProfile)

map2 . , - .

+7

Source: https://habr.com/ru/post/1654019/


All Articles