Skip to content

Instantly share code, notes, and snippets.

@travispaul
Last active January 26, 2018 12:43
Show Gist options
  • Save travispaul/a83a79c2936a26850637c0aefdd26c35 to your computer and use it in GitHub Desktop.
Save travispaul/a83a79c2936a26850637c0aefdd26c35 to your computer and use it in GitHub Desktop.
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
Copy link

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

@travispaul
Copy link
Author

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