I have a node.js script which performs a lot of asynchronous operations with mongoose. My problem is that when it finishes, my terminal won't return to the bash prompt that called the script.
This is some of my code:
'use strict';
// Set default node environment to development process.env.NODE_ENV = process.env.NODE_ENV || 'development';
...
// Connect to database
mongoose.connect(config.mongo.uri, config.mongo.options);
var sendYouHaveNewEmail = function (invoice, to_user) {
var data = {
from: 'asfd@asfd.adsf',
to: to_user.email,
subject: 'You have new Stuff',
html: jade.renderFile(__dirname + '/../' + 'mytemplate.jade')
})
};
mailer.send(data, function (error) {
if (error) {
console.log("An error occurred sending a email to", to_user.email);
}
});
};
Schedule.find({name: 'myname'}).exec()
.then(function (results) {
var ids = _.map(results, function (schedule) {
return schedule.person_id;
});
Person.find({_id: {$in: ids}}).exec()
.then(function (persons) {
if (persons.length == 0) return;
_.forEach(persons, function (person) {
Profile.findOne({user_id: person._id}).exec()
.then(function (profile) {
...
console.log("I'm done");
})
.end(function (err) {
console.log("An error occurred ", err)
});
});
})
.end(function (err) {
console.log("An error occurred ", err);
});
})
.end(function (err) {
console.log("An error occurred retrieving Schedule list", err);
});
Why is this happening? Is this wrong?