32

In Elm, and specifically with the Elm Architecture when the app first starts the init function can return a Cmd Msg that is executed. We can use this for sending http requests or send a message to native Javascript via Elm ports.

My question is, how can I send multiple commands that should be executed in init?

For example I can do something like:

init : (Model, Cmd Msg)
init =
  (Model "" [], (Ports.messageToJs "Hello JS"))

And I can do something like:

url : String
url =
     "http://some-api-url.com"
...

fetchCmd : Cmd Msg
fetchCmd =
    Task.perform FetchError FetchSuccess fetchTask


init : (Model, Cmd Msg)
init =
  (Model "" [], fetchCmd)

How can I return both commands at same time from init?

I have seen Task.sequence and even Task.parallel but they appear to be good for running multiple tasks, not specifically commands.

antfx
  • 3,205
  • 3
  • 35
  • 45

2 Answers2

60

Use Platform.Cmd.batch (docs):

init : (Model, Cmd Msg)
init =
  ( Model "" []
  , Cmd.batch [fetchCmd, Ports.messageToJs "Hello JS")]
  )
Eleanor Holley
  • 691
  • 1
  • 7
  • 27
Søren Debois
  • 5,598
  • 26
  • 48
  • Do commands run in parallel or are they serialized? I'm thinking of a batch of multiple HTTP gets that would take a long time if serialized. – goertzenator Aug 26 '16 at 14:33
  • 1
    @goertzenator they run in parallel, not in series – antfx Sep 24 '16 at 14:33
  • 1
    The order is not specified. As JavaScript runs with a single thread one will run before the other, but you should not make any assumptions about what that order will be. – Zachary K Jun 20 '17 at 13:01
5

Do as Sören says, or use the newer, equivalent "bang" -syntax :

init : (Model, Cmd Msg)
init =
  ( Model "" [] )
  ! [fetchCmd, Ports.messageToJs "Hello JS"]
swelet
  • 8,192
  • 5
  • 33
  • 45