2
\$\begingroup\$

In my application I need some resources to be loaded and I have services to load each of them and then I need some point to know that all requests finished. First thought was to use $q.all with array of promises from that services. But it would be resolved only if all promises resolved which is now always the right case because some of them may be rejected. Finally I ended up with this code:

.service 'dataRepository', ($q, Categories, Items, Settings, Session) ->
    data: {}
    fetch: ->
        res = $q.defer()
        foo = 
            categories: Categories.fetch()
            items: Items.fetch()
            settings: Settings.fetch()
            user: Session.fetch()

        cEnded = 0
        for k, p of foo
            p.then do (k) =>
                (result) => 
                    @data[k] = result 

            p.finally do (k) =>
                =>
                    cEnded++
                    if cEnded is _.size foo
                        res.resolve @data
        res.promise

I can put result of dataRepository.fetch() in resolve of $urlRouterProvider of ui-router and in my controllers I can be sure that data loading finished.

But this is not looking like a good solution. So the question is, are there better ways to wait for the requests pool?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Actually I'm surprised there isn't a $q.some or so to do exactly that.

I think this is a good solution for the problem, though putting it in a separate function would be nice. (Can't think of any reasons to not do it like this either.)

\$\endgroup\$
3
  • \$\begingroup\$ you mean to extend $q? \$\endgroup\$
    – SET
    Jan 27, 2015 at 0:06
  • \$\begingroup\$ That's a possibility of course. \$\endgroup\$
    – ferada
    Jan 27, 2015 at 1:06
  • 1
    \$\begingroup\$ Here you can find some ideas to extend $q: stackoverflow.com/questions/18888104/… \$\endgroup\$
    – Dieterg
    Jan 27, 2015 at 7:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.