Skip to content

Instantly share code, notes, and snippets.

@travispaul travispaul/answer.md
Last active Jan 26, 2018

Embed
What would you like to do?
module.exports how to return a function value?

The return value of getAOLDataCount is undefined. You're returning the aolCount variable from within an anonymous function in your .then() call and it's not being returned.

It's basically the same as this:

module.exports = {
    getAOLDataCount:  function () {
        wd = new WeeklyData(sequelize, Sequelize.DataTypes);
        wd.count({where: {week:201740, project: 8}}).then(function (aolCount) {
            console.log(aolCount);
            return aolCount;
        });
        return undefined;
    }
};

Since, wd.count is asynchronous you cannot return aolCount this way, you will have to restructure your code.

Consider this approach (though there are many you could take) which passes the response object to your module which then can call .send().

app.js

app.get('/sample', function (req, res, next) {
   aol.getAOLDataCount(res);
});

aol.js

module.exports = {
    getAOLDataCount:  function (res) {
        wd = new WeeklyData(sequelize, Sequelize.DataTypes);
        wd.count({where: {week:201740, project: 8}}).then(function (aolCount) {
            console.log(aolCount);
            res.send(aolCount);
        });
    }
};
@simonjcarr

This comment has been minimized.

Copy link

simonjcarr commented Jan 26, 2018

Thank you. This is a brilliant explanation and has really helped my understanding of Async functions.

@travispaul

This comment has been minimized.

Copy link
Owner Author

travispaul commented Jan 26, 2018

Hi @simonjcarr, no problem, glad to help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.