Can this async flow be done better?

We have a part of our app which is proving to be buggy and hard to maintain. When a user arrives to this page we need to:

  • Fetch a couple of values from local storage
  • Fetch a couple collections from our API
  • When we have all these four things we need to request a report from our API.
  • If any of these things fails we provide a fallback report (e.g. local storage never returns).

This is an simplified example of what we have

  • Call the API and get a message back
  • When we get the data check if we can proceed
  • Request local storage via ports
  • Listen to a subscription for getting local storage
  • When we get all the local storage value check if we can proceed
  • When we have all the values (api data + LS) request the report
  • Add a timeout via Procees.sleep
  • On the timeout check if we are still waiting for data or local storage, if so fetch the fallback report

Optimally I would like to create one cmd that does all these things and just call update once when done, with either the all data or the error. Similar to what you could do in JS with Promise.all. But as local storage value arrive via subscriptions, there seems to be no way to put all these things together.

But I’m curious to hear if there are better approaches than what we are doing. Thanks.

I think you’ll be helped by using e.g. elm-porter, which wraps port-pairs (the sending Cmd port and the receiving Sub port) and allows you to chain multiple of these actions together, meaning that your logic can be written as one sequence (e.g. the first high-level list of steps you provide).

1 Like

I’m using the-sett/elm-state-machines to ensure I correctly sequence a lot of Cmd/Sub calls.

1 Like

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