JavaScript can do an http request with closure, but how does that work in Elm?

In JavaScript it’s pretty common to use closures, very handy for example when making http requests, and remembering what you asked for. I.e.

var id = 3;
http_request (function (result) {
  // I know I made the request for id 3, 
  // even though the result variable may not mention this
});

How do you do this in Elm? It seems that in Elm the result needs to tell my program what it was for.

Any suggestions?

Need more coffee in the morning :slight_smile: But as usual. phrasing the question is answering it, so may have helped me.

This is how to do it obviously:

Http.send (Foo id) request

1 Like

What’s foo msg signature and request implementation? I need more details.

request = 
    Http.get "/foo" decodeResponse

Msg =
    Foo Int (Result Http.Error ValidResponse)

In case it isn’t clear, I answered my own question.

request : Http.Request ValidResponse
request = Http.get “/foo” decodeResponse

type Msg = Foo Int (Result Http.Error ValidResponse)

Now I noticed that you already solved your problem. This is a nice way, but if I would need this information later, I would store in the model instead of passing in the first parameter. But you did right for your case

The problem is that this does not work: http requests are asynchronous, so you cannot control when a response is received, so you cannot match a state in your model against a randomly incoming response. It might be a delayed and stale response.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.