Skip to content

Instantly share code, notes, and snippets.

@thejhh
Created December 17, 2012 08:40
Show Gist options
  • Select an option

  • Save thejhh/4316742 to your computer and use it in GitHub Desktop.

Select an option

Save thejhh/4316742 to your computer and use it in GitHub Desktop.
Example use of databases with Promises
var Q = require('q');
var DB = require('db');
// These DB initializations would probably not be synchronous in a real
// app. You could use Q.spread(), etc. See sample #2.
var db1 = DB.openSync("db1");
var db2 = DB.openSync("db2");
var db3 = DB.openSync("db3");
/** Sample implementation of db.queryRow(). Please note that it should
* be included in the db library. However I think implementing it here
* is a great example of using Promises.
*/
DB.prototype.queryRow = function(str, opts) {
return this.query(str, opts).when(function(rows) {
var row = rows.shift();
if(!row) return new TypeError("No enough rows!");
return row;
};
};
/* Our sample #1. It's our own function that returns a promise. */
function sample() {
var result1, result2;
return db1.queryRow("SELECT FROM foo WHERE id = {id}", {'id':1}).when(function(row1) {
result1 = row1;
if(result1.title) return result1.title;
return db2.queryRow("SELECT FROM bar WHERE foo = {foo}", {'foo':result1.id}).when(function(row2) {
result2 = row2;
return result2.title;
});
}).when(function(title) {
if(result1) console.log("result1 = " + JSON.stringify(result1));
if(result2) console.log("result2 = " + JSON.stringify(result2));
return "Title was " + title;
});
} // end of sample
// Code for sample 1
sample().when(function(title) {
console.log("Title = " + title);
}).fail(function(err) {
console.error("ERROR: " + err);
}).done();
/** Sample #2 performing multiple operations at the same time and
* collecting results from all of them into one single response.
*/
function sample2() {
// db.queryRow is same as db.query but it does the results.shift()
// for us and verifies that it's not undefined.
var a = db1.queryRow("SELECT COUNT(*) AS rows FROM foo");
var b = db2.queryRow("SELECT COUNT(*) AS rows FROM bar");
var c = db3.queryRow("SELECT COUNT(*) AS rows FROM world");
return Q.spread([a, b, c], function (a, b, c) {
return a.rows + b.rows + c.rows;
});
}
// Code for sample 2
sample2().when(function(rows) {
console.log("Databases have total of " + rows + " rows.");
}).fail(function(err) {
console.error("ERROR: " + err);
}).done();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment