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 function email_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~
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.