Search code examples
javascriptnode.jsdeferred-execution

How do i implement this pattern in node js?


I am writing a data access layer where in my dalmethod will be called & after work is done by the callers, I have to close the db.

I dont want to bother the callers for closing my db (or performing some other operations).

Basically i am looking out for some synchronicity in my asynchronous operations (promises?).

Following is a pseudo code.

//For simplicity , assume they are in same file.

function Caller ()
{
  dalmethod(function(err,db){
     do some thing
     // I am done here
   });

}

function dalmethod(callback)
{
// Connect database & call this function

  callback(somevalue,db);
 //after call back function is executed call some more methods. such as closing the db.
  // db.close();
}

Caller();

Solution

  • You're right, it's a classic with a promise:

    function Caller() {
    
      dalmethod( function(err, db) {
    
         // Let promisification of anonymous callback
         return new Promise(( resolve, reject ) => {
           console.log('do somethings');
    
           // Simulate processing errors
           var dice = Math.random();
           if (dice>0.5) {
             resolve( 'Some result' );
           } else {
             reject( new Error('Something went wrong') );
           }
         });
    
       });    
    }
    
    function dalmethod(callback) {
      var somevalue, db;
      callback(somevalue,db)
        .then(
          response => { console.log( response, 'close db' ); },
          reject => { console.log(reject); }
        );
    }
    
    Caller();