Ondrej Sevcik Ondrej Sevcik - 2 months ago 23
HTTP Question

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

I want to load user profile before rendering something into the page but the whole user profile is composed of different parts that are loaded by multiple HTTP requests.

So far I'm loading user profile in sequence (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 that's not very effective. Is there a simple way how to perform a bunch of Http requests and return just one complete value?

Something like this

init =
(initialModel, loadUserProfile userId LoadUserProfileFail LoadUserProfileSuccess)

....

Answer

You can achieve this using Task.map2:

Task.perform LoadUserProfileFail LoadUserProfileSuccess
  <| Task.map2 (\userName companyInfo -> { userName = userName, companyInfo = companyInfo })
       (Http.get userDecoder userNameGetUrl)
       (Http.get companyInfoDecoder companyInfoGetUrl)

You can then get rid of the individual LoadUserName... and LoadCompanyInfo... Msgs.

map2 will only succeed once both tasks succeed. It will fail if any of the tasks fail.