0

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?

danielrvt
  • 10,177
  • 20
  • 80
  • 121
  • 1
    Node will keep running as long as further events are expected to be added to the event loop. Best guess is that the connection to Mongo isn't being closed after the queries have completed. But, you'll have to share at least some of your code for us to properly help. – Jonathan Lonowski Jan 15 '15 at 15:51
  • @JonathanLonowski I've just added some example code, my actual code is working without errors. – danielrvt Jan 15 '15 at 16:03
  • Related: [Do I need to manually close a mongoose connection?](http://stackoverflow.com/questions/19371821/do-i-need-to-manually-close-a-mongoose-connection) – Jonathan Lonowski Jan 15 '15 at 16:17

0 Answers0