shanwar shanwar - 6 months ago 32
Node.js Question

Using promises to wait for function to finish

I've read some tutorials online for the Promises method but I'm still a bit confused.
I have a Node app.js which performs several functions including connecting to a db.

db.connect(function(err) {
if(err) {
logger.raiseAlarmFatal(logger.alarmId.INIT,null,'An error occurred while connecting to db.', err);

Now I have written a mocha unit test suite, which encapsulates this app and performs several request calls to it. In some cases what occurs is that the the test initializes without confirmation that the db has successfully connected i.e:
has been performed.

How would I implement the promises method to this bit of asynchronous code, and if not promises, what should I use ? I have already tried event emitter but this still does not satisfy all the requirements and causes failures during cleanup.

Answer Source

If you're using mocha, you should use asynchronous code approach. This way you can instruct mocha to wait for you to call done function before it goes on with the rest.

This would get you started:

describe('my test', function() {
  before(function(done) {
    db.connect(function(err) {

  it('should do some testing', function() {
     // This test is run AFTER 'before' function has finished
     // i.e. after setupServer has called done function

assuming that your setupServer calls the done function when it's done:

function setupServer(done) {
  // do what I need to do
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download