Last active
December 20, 2015 00:49
-
-
Save yeaha/6044317 to your computer and use it in GitHub Desktop.
把any-db的查询用Q封装为promise风格
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var _ = require('underscore'); | |
var Q = require('q'); | |
var pool = require('any-db').createPool('postgres://dev:[email protected]/lysine', {name: 'test', min: 3, max: 10, log: true}); | |
function query(sql, params) { | |
return _query(sql, params, false); | |
} | |
function stream_query(sql, params) { | |
return _query(sql, params, true); | |
} | |
function _query(sql, params, stream) { | |
var query; | |
var defered = Q.defer(); | |
var args = [sql, params || []]; | |
stream = _.isUndefined(stream) ? false : !!stream; | |
pool.query.apply(pool, args) | |
.on('row', function(row, res) { | |
if (!stream) res.addRow(row); | |
defered.notify(row); | |
}) | |
.on('error', function(err) { defered.reject('error'); }) | |
.on('end', function(res) { defered.resolve(res); }); | |
return defered.promise; | |
} | |
stream_query('select now()', []) | |
.progress(function(row) { | |
console.log('progress'); | |
console.log(row); | |
}) | |
.then(function(res) { | |
console.log('resolve'); | |
console.log(res); | |
}) | |
.catch(function(err) { | |
console.log('reject'); | |
console.log(err); | |
}) | |
.finally(_.bind(pool.close, pool)); | |
function _exit() { | |
pool.close(); | |
console.log('pool closed'); | |
} | |
process.on('SIGINT', _exit); | |
process.on('SIGHUP', _exit); | |
process.on('SIGQUIT', _exit); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment