Skip to content

Instantly share code, notes, and snippets.

@veer66
Last active December 15, 2015 05:09
Show Gist options
  • Save veer66/5206903 to your computer and use it in GitHub Desktop.
Save veer66/5206903 to your computer and use it in GitHub Desktop.
Loop + queries + Q
var mysql = require('mysql');
var Q = require("q");
function createConnection() {
var conn = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 't2'
});
conn.connect();
return conn;
}
var deferred = Q.defer();
var promises = [];
var conn = createConnection();
conn.query("SELECT * FROM corpora WHERE `type` = 'dependency' AND `status` = 'beta'",
function(err, rows, fields) {
if(err) {
deferred.reject(new Error(err));
} else {
deferred.resolve(rows.map(function(row) {
return row['id'];
}));
}
});
var d2_list = [];
var d3_list = [];
var d1 = deferred.promise.then(function(corpus_id_list) {
corpus_id_list.forEach(function(corpus_id) {
var d2 = Q.defer();
conn.query("SELECT id FROM textunits WHERE corpus_id = ?", [corpus_id],
function(err, rows) {
if(err) {
d2.reject(new Error(err));
} else {
d2.resolve(rows.map(function(row) {
return row['id'];
}));
}
});
d2_list.push(d2.promise.then(function(textunit_id_list) {
textunit_id_list.forEach(function(textunit_id) {
var d3 = Q.defer();
conn.query("SELECT * FROM annots WHERE textunit_id = ? ORDER BY rev DESC", [textunit_id],
function(err, rows) {
if(err) {
d3.reject(new Error(err));
} else {
d3.resolve(rows[0]);
}
});
d3_list.push(d3.promise.then(function(annot) {
console.log(annot.id);
}));
});
}));
});
}).fin(function() {
console.log("FIN 1", d2_list.length);
Q.all(d2_list).fin(function() {
console.log("FIN 2", d3_list.length);
Q.all(d3_list).fin(function() {
console.log("END");
conn.end();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment