shanwar
shanwar

Reputation: 329

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) {
     setupServer();
     if(err) {
        logger.raiseAlarmFatal(logger.alarmId.INIT,null,'An error occurred while connecting to db.', err);
        return;
      }

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: setupServer() 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.

Upvotes: 0

Views: 1161

Answers (2)

Ozan
Ozan

Reputation: 3739

You will need to use Promise inside the body of function that has async work. For your case, I think that is setupServer() which you said contains ajax requests.

conts setupServer = () => {
  return new Promise((resolve, reject) => {
    //async work
    //get requests and post requests
    if (true)
      resolve(result); //call this when you are sure all work including async has been successfully completed.
    else
      reject(error); //call this when there has been an error
  });
}


setupServer().then(result => {
  //...
  //this will run when promise is resolved
}, error => {
  //...
  //this will run when promise is rejected
});

For further reading:

Upvotes: 0

Yan Foto
Yan Foto

Reputation: 11378

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) {
      setupServer(done);
    });
  })

  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
  done();
}

Upvotes: 1

Related Questions