1

Assume this simple module:

var mongoose = require('mongoose-util');

mongoose.myOwnCreateConnection(function(err, connection) {
  if(err) {
     console.log('log error somehow and make it die');
     module.exports = null;
  } else { 
     module.exports = connection;
  }
});

It won't work obviously, but how to manage that calls in context module initialization? What is the best practice here? Do I need to use function declaration only in module init? Thanks in advance. I am asking because express has app module where everything is initialized.

7
  • mongoose createConnection doesn't take a function as its argument: mongoosejs.com/docs/api.html#index_Mongoose-createConnection Commented Aug 13, 2015 at 6:32
  • it's not clear what are you trying to achieve here Commented Aug 13, 2015 at 6:33
  • Sorry, that was a simplifying, I will edit this ridiculously insane example :) Commented Aug 13, 2015 at 6:33
  • What I want to achieve is to export connection object in module. That is example, code is more complex but it does not matter here, it is not working even for this. Commented Aug 13, 2015 at 6:35
  • 1
    stackoverflow.com/questions/20238829/… Commented Aug 13, 2015 at 6:52

1 Answer 1

1

Require is synchronous operation. So this will not work, you can use this:

Asynchronous nodejs module exports

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

1 Comment

That is quite clean solution, but using this I will just 'delay' (or rather postpone) async to another module - because I am using this 'async' module in other 'sync' modules, so it will require to make another async modules etc. I hope you get my point, but this solution is really nice.

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.