cphill
cphill

Reputation: 5914

JavaScript Promises Not Returning Object

I have an issue where I am using Sequelize to run a query and within the first then statment return the object and then run a query on a different table. After that query is run I have an additional then statement that should pass the returned objects to be able to access in my view. Unfortunately, the second query does not return an object as the console log returns undefined for the second log (Check console.log(member)). Any reason why this is happening or what I am doing wrong? The queries come back with the right statements.

appRoutes.route('/settings/add-users')

    .get(function(req, res){
        models.Organization.find({
            where: {
                organizationId: req.user.organizationId
            }, attributes: ['organizationId', 'organizationName','admin','members']
        }).then(function(organization, member){
            models.Member.findAll({
                where: {
                    organizationId: organization.organizationId
                }, attributes: ['memberEmail']
            });
            return organization;
        }).then(function(organization, member){

            console.log(organization);
            console.log(member);
            res.render('pages/app/add-users.hbs',{
                user: req.user,
                organization: organization,
                member: member
            });
        }).catch(function(error){
            res.send(error);
            console.log(error);
        })
    });

Upvotes: 0

Views: 269

Answers (1)

Paul
Paul

Reputation: 141829

A promise can only resolve to a single value. You are returning organization again from your then, so the next then gets that as its value. You can use an object to achieve the behaviour you want.

appRoutes.route('/settings/add-users')

    .get(function(req, res){
        var organization;

        models.Organization.find({
            where: {
                organizationId: req.user.organizationId
            }, attributes: ['organizationId', 'organizationName','admin','members']
        }).then(function(_organization){
            organization = _organization;
            return models.Member.findAll({
                where: {
                    organizationId: organization.organizationId
                }, attributes: ['memberEmail']
            });
        }).then(function(member){

            console.log(organization);
            console.log(member);
            res.render('pages/app/add-users.hbs',{
                user: req.user,
                organization: organization,
                member: member
            });
        }).catch(function(error){
            res.send(error);
            console.log(error);
        })
    });

Upvotes: 1

Related Questions