Permalink
Browse files

simplify deferred open

  • Loading branch information...
1 parent 13cfb43 commit d189491fe5d35fb7afa13610adc4710590bf6648 @dominictarr dominictarr committed Mar 3, 2013
Showing with 20 additions and 17 deletions.
  1. +20 −17 lib/levelup.js
View
@@ -118,6 +118,21 @@ var leveldown = require('leveldown')
}.bind(this))
}.bind(this)
+ var deferred = {}
+ var self = this
+
+ ;['get', 'put', 'batch', 'del', 'approximateSize']
+ .forEach(function (name) {
+ deferred[name] = function () {
+ var args = [].slice.call(arguments)
+ self.once('ready', function () {
+ self._db[name].apply(self._db, args)
+ })
+ }
+ })
+
+ this._db = deferred
+
execute()
this.emit('opening')
}
@@ -148,18 +163,6 @@ var leveldown = require('leveldown')
LevelUP.prototype.isClosed = function () { return (/^clos/).test(status) }
- function defer(db, fun) {
- return function () {
- if(isOpening()) {
- var args = [].slice.call(arguments)
- return db.once('ready', function () {
- db._db[fun].apply(db._db, args)
- })
- }
- return db._db[fun].apply(db._db, arguments)
- }
- }
-
LevelUP.prototype.get = function (key_, options, callback) {
var key
, valueEnc
@@ -177,7 +180,7 @@ var leveldown = require('leveldown')
valueEnc = valueEncoding(options)
options.asBuffer = valueEnc != 'utf8' && valueEnc != 'json'
- defer(this, 'get')(key, options, function (err, value) {
+ this._db.get(key, options, function (err, value) {
if (err) {
err = new errors.NotFoundError(
'Key not found in database [' + key_ + ']')
@@ -204,7 +207,7 @@ var leveldown = require('leveldown')
key = toSlice[keyEncoding(options)](key_)
value = toSlice[valueEncoding(options)](value_)
- defer(this, 'put')(key, value, options, function (err) {
+ this._db.put(key, value, options, function (err) {
if (err) {
err = new errors.WriteError(err)
return dispatchError(err, callback)
@@ -230,7 +233,7 @@ var leveldown = require('leveldown')
options = getOptions(options)
key = toSlice[keyEncoding(options)](key_)
- defer(this, 'del')(key, options, function (err) {
+ this._db.del(key, options, function (err) {
if (err) {
err = new errors.WriteError(err)
return dispatchError(err, callback)
@@ -280,7 +283,7 @@ var leveldown = require('leveldown')
arr = arr_
}
- defer(this, 'batch')(arr, options, function (err) {
+ this._db.batch(arr, options, function (err) {
if (err) {
err = new errors.WriteError(err)
return dispatchError(err, callback)
@@ -300,7 +303,7 @@ var leveldown = require('leveldown')
return dispatchError(err, callback)
}
- defer(this, 'approximateSize')(start, end, function(err, size) {
+ this._db.approximateSize(start, end, function(err, size) {
if (err) {
err = new errors.OpenError(err)
return dispatchError(err, callback)

0 comments on commit d189491

Please sign in to comment.