dennismende
dennismende

Reputation: 21

EmberJS fulfill multiple nested promises

I want to return an array of objects. My code looks like this:

var apps = [];

    this.get('groups').then(function(groups)
    {
        groups.forEach(function(group)
        {
            self.store.find('module', group.get('module').get('id')).then(function(module)
            {
                self.store.find('app', module.get('app').get('id')).then(function(app)
                {
                    if(!apps.contains(app))
                        apps.pushObject(app);
                });
            });
        });
    });

I want to return all apps after foreach-loop is fulfilled, but I have no idea.

Upvotes: 2

Views: 526

Answers (1)

panta82
panta82

Reputation: 2721

You must always return a promise to keep building the chain.

var self = this;

return this.get('groups')
    // Return an app for each group
    .then(function (groups) {
        return Ember.RSVP.Promise.all(groups.map(function (group) {
            return self.store.find('module', group.get('module.id'))
                .then(function (module) {
                    return self.store.find('app', module.get('app.id'));
                });
        }));
    })
    // Filter out duplicates
    .then(function (apps) {
        return apps.uniq();
    });

Upvotes: 2

Related Questions