0

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();
Abdul Rehman Sayed
  • 6,532
  • 7
  • 45
  • 74
  • Simplest solution given your current code is to close the db within your anonymous callback. – Ezra Chang May 27 '16 at 07:36
  • Not entirely clear what your question is here. Do you want to perform a number of tasks before calling back, or do you want to callack after dalmethod has completed, and THEN close the database? – Mitch May 27 '16 at 07:36
  • i want to call the callback & after it is completed, close the db inside dalmethod. – Abdul Rehman Sayed May 27 '16 at 08:39

1 Answers1

0

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();
stdob--
  • 28,222
  • 5
  • 58
  • 73