I consider myself a very experienced node.js developer.
Yet I still wonder if there is a better way to write the following code so I don\'t get the pyramid of doom..
I break each level of the pyramid of doom into a function and chain them one to the other. I think it is a lot easier to follow. In the example above i'd do it as follows.
ms.async.eachSeries(arrWords, function (key, asyncCallback) {
var pgCB;
var pgClient;
var connect = function () {
pg.connect(pgconn.dbserver('galaxy'), function (err, _pgClient, _pgCB) {
pgClient = _pgClient;
pgCB = _pgCB;
findKey();
});
};
var findKey = function () {
statement = "SELECT * FROM localization_strings WHERE local_id = 10 AND string_key = '" + key[0] + "'";
pgClient.query(statement, function (err, result) {
if (pgconn.handleError(err, pgCB, pgClient))
return;
// if key doesn't exist go ahead and insert it
if (result.rows.length == 0) {
getId();
return;
}
pgCB();
asyncCallback();
});
};
var getId = function () {
statement = "SELECT nextval('last_resource_bundle_string_id')";
pgClient.query(statement, function (err, result) {
if (pgconn.handleError(err, pgCB, pgClient))
return;
insertKey();
});
};
var insertKey = function () {
var insertIdOffset = parseInt(result.rows[0].nextval);
statement = "INSERT INTO localization_strings (resource_bundle_string_id, string_key, string_revision, string_text,modified_date,local_id, bundle_id) VALUES ";
statement += " (" + insertIdOffset + ",'" + key[0] + "'," + 0 + ",'" + englishDictionary[key[0]] + "'," + 0 + ",10,20)";
ms.log(statement);
pgClient.query(statement, function (err, result) {
if (pgconn.handleError(err, pgCB, pgClient))
return;
pgCB();
asyncCallback();
});
};
connect();
});