Permalink
Browse files

Use async library to tighten up code a bit

  • Loading branch information...
kunklejr committed Apr 29, 2012
1 parent 7826600 commit cb550dd4f614972c1ce278f3004104e39f06d1b9
Showing with 20 additions and 32 deletions.
  1. +17 −31 lib/store.js
  2. +3 −1 package.json
View
@@ -2,6 +2,7 @@ var fs = require('fs');
var path = require('path');
var events = require('events');
var util = require('util');
+var async = require('async');
var jsonFormat = require('./format/json');
var idgen = require('./idgen');
@@ -23,6 +24,10 @@ function filterFiles(files) {
return results;
}
+function isDeletedError(err) {
+ return err && err.code === 'ENOENT';
+}
+
var Store = module.exports = function (docdir, options) {
options = options || {};
this.docdir = docdir;
@@ -71,24 +76,12 @@ Store.prototype.clear = function (callback) {
}
files = filterFiles.call(this, files);
- var length = files.length;
- if (length === 0) {
- return callback(null);
- }
-
- var unlinked = 0;
-
- for (var i = 0; i < length; i++) {
- var id = getIdFromFilename(files[i]);
+ async.forEach(files, function(file, done) {
+ var id = getIdFromFilename(file);
this.remove(id, function(err) {
- if (err && err.code !== 'ENOENT') {
- return callback(err);
- }
- if (length === ++unlinked) {
- return callback(null);
- }
+ isDeletedError(err) ? done() : done(err);
});
- }
+ }.bind(this), callback);
}.bind(this));
};
@@ -111,31 +104,24 @@ Store.prototype.scan = function (filter, callback) { // callback is optional, ma
}
files = filterFiles.call(this, files);
- var length = files.length;
- if (length === 0) {
- return onEnd();
- }
-
- var read = 0;
-
- for (var i = 0; i < length; i++) {
- var id = getIdFromFilename(files[i]);
+ async.forEach(files, function(file, done) {
+ var id = getIdFromFilename(file);
this.get(id, function(err, doc) {
- var deleted = err && err.code === 'ENOENT';
+ var deleted = isDeletedError(err);
if (err && !deleted) {
- return onErr(err);
+ return done(err);
}
if (!deleted && filter(doc)) {
onDoc(doc);
}
- if (length === ++read) {
- onEnd();
- }
+ done();
});
- }
+ }.bind(this), function(err) {
+ err ? onErr(err) : onEnd();
+ });
}.bind(this));
return callback ? undefined : emitter;
View
@@ -17,7 +17,9 @@
"engines": {
"node": "~0.6.1"
},
- "dependencies": {},
+ "dependencies": {
+ "async": "0.1.18"
+ },
"devDependencies": {
"chai": "~0.5.1",
"mocha": "~1.0.0"

0 comments on commit cb550dd

Please sign in to comment.