How can I clean up this code? Confusion regarding promises

Hello Ionic community! I’m still learning Ionic and having a little trouble trying to clean up my code.

This is the code in question

Problem: the Rivers factory’s method is returning a promise, I want it to just return an object. Specifically rivers in this case. In a nutshell what I’m trying to do with this Rivers.all() method is:

  1. Grab the user’s location, specifically their state abbreviation
  2. Get a list of rivers from the web service
  3. Return an object with this information.

The idea is I can have a clean controller like the above code, but still grab all the data I need using that service… the promises just confuse me a bit. Sure, I could use .then() in my controller, but it seems messy to do it like that. What’s preferred here?

Thanks in advance to anyone who can shed some light on this!

I believe I found the answer, except now I’ve got another problem. The tabs and the title (in the header) are missing on the initial page load until the data is resolved. I expected the tabs to be visible prior to the resolve happening, is this incorrect?

The code now looks like this.

Seems to be some code missing here?

@aaronksaunders What else would you like to see? I tried to post only the most relevant pieces of code?

i cannot see your error because there is nothing to run? I would have to try an eyeball it to see if there is an error.

But yes, the resolve must return before the controller and view are activated. If you need the view to render first than move the code into the controller is the only solution… i think?

Okay, next time I’ll be sure to post a runnable version, I see what you’re saying. Sorry about that! That definitely answers my question. In my case the resolve can take a little while and I’d like to show some sort of loading indicator… is there a way I could do that while still using resolve ?

Bit difficult to look at this without a running example so my fork will most likely have some errors. It’s more to show using a promise chain so you can separate the purpose of both services. In short - its better to have both service methods to concentrate on one task - eg fetching data from another service and then fetching its own data could lead to problems with scaling , testing etc.

Lean controllers are great but not at the expense of other principles that get overlooked so creating a promise chain in your controller allows much more fine grained control over the data coming back and what you can do with.

As mentioned code is not tested at all but you should get the idea :smile: