Example of querying using Promises

Tom Conlon edited this page May 24, 2014 · 1 revision
var
   fb = require("node-firebird"),  // firebird lib
   q = require('q'),               // promises lib
   db,                             // this will store the global db object 
   cfg;                            // cfg object  

cfg =
{
   host: '127.0.0.1',
   port: 3050,
   database: 'C:\\A.FDB',
   user: 'SYSDBA',
   password: 'masterkey'
};


/*------------------------------ UTILITY -------------------------------*/
function ab2str(buf) {
   return String.fromCharCode.apply(null, new Uint16Array(buf));
}

function str2ab(str) {
   var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
   var bufView = new Uint16Array(buf);
   for (var i=0, strLen=str.length; i<strLen; i++) {
      bufView[i] = str.charCodeAt(i);
   }
   return buf;
}

/*------------------------------ CONNECT/DISCONNECT -------------------------------*/
connectToDB = function (acfg){
   var def = q.defer();

   fb.attach( acfg,
      function(err, db){
         err ? def.reject(err) : def.resolve(db);
      }
   );
   return def.promise;
};

disconnectFromDB = function() {
   db.detach(
      function(){
         console.log('database detached');
      }
   );
};

/*------------------------------ QUERY -------------------------------*/
queryDB = function(sql){
   var def = q.defer();

   connectToDB(cfg).then(
      // success
      function(dbconn){
         db = dbconn;
         db.query(sql,
         function(err, rs){
            err ? def.reject(err) : def.resolve(rs);
         });
      },
      // fail
      function(err)  {
         console.log(err);
      }
   );
   return def.promise;
};


/*------------------------------------------------
example of querying using promises
------------------------------------------------*/
queryDB( "select id, name from users order by id").then(
      // success
      function(rs) {
         rs.forEach( function(row){
            console.log( row.id, ab2str(row.name));
         });
         disconnectFromDB();
      },
      // fail
      function(err)  {
         console.log(err);
         disconnectFromDB();
      }
   );
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.