1

I am building an app using node.js and wanted to confirm an issue regarding modules and node's asynchronous nature. If I have a module such as:

var email_list = function() {
    //perform some database query or calculation
}

exports.email_to = function() {

    email_list.forEach(function(email) {
        console.log(email);
    });

};

And in another file, I call my email_to method, does the functionemail_list get called before my email_to function gets called? If not, is there a way to guarantee that the email_to function gets called after the email_list function?

Thanks in advance~

3
  • 1
    Your email_list function is not going to work the way you expect since it contains a promise Commented May 2, 2016 at 19:37
  • thanks - i just edited it to make it more generic Commented May 2, 2016 at 19:41
  • There are no calls to the email_list function in your code, so no, it wouldn't be called before email_to. Functions are only called when you call them. Commented May 2, 2016 at 19:44

1 Answer 1

2

I commented, but I'll elaborate a little bit. Your going to want to do something like this:

var email_list = function() {

    return knex('email_list').where({
            verified: true
        });    
};

exports.email_to = function() {

    var response = email_list()
        .then(function(emailList){
            emailList.forEach(function(email){
                console.log(email);
            });
        });
};

There is a lot of documentation out there about the event lifecycle of Node and Javascript in general. On a really high level, you are going to want to study how promises and callbacks work. That is how you "guarantee" things get called when you would expect them to.

In this case, email_list returns a promise. You can use the result of that promise in your email_to function. You wait for the result of that promise by using then

Sign up to request clarification or add additional context in comments.

1 Comment

Super high level. I hope this didn't make your question more confusing.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.