Browse Source

Refactor promise usage and return it only if no callback provided

feature/remove-domains
Jonathan 9 years ago
parent
commit
5dae350582
  1. 48
      lib/multi_caching.js

48
lib/multi_caching.js

@ -53,7 +53,11 @@ var multiCaching = function(caches, options) {
options = {}; options = {};
} }
var defer = Promise.defer(); var promised = false;
if (!cb) {
cb = Promise.defer();
promised = true;
}
var i = 0; var i = 0;
async.eachSeries(caches, function(cache, next) { async.eachSeries(caches, function(cache, next) {
@ -66,10 +70,10 @@ var multiCaching = function(caches, options) {
if (_isCacheableValue(result)) { if (_isCacheableValue(result)) {
// break out of async loop. // break out of async loop.
if (typeof cb === 'function') { if (!promised) {
return cb(err, result, i); return cb(err, result, i);
} }
return defer.resolve(result); return cb.resolve(result);
} }
i += 1; i += 1;
@ -78,21 +82,27 @@ var multiCaching = function(caches, options) {
cache.store.get(key, options, callback); cache.store.get(key, options, callback);
}, function(err, result) { }, function(err, result) {
if (typeof cb === 'function') { if (!promised) {
cb(err, result); return cb(err, result);
} }
if (err) { return (err) ? cb.reject(err) : cb.resolve(result);
return defer.reject(err);
}
defer.resolve(result);
}); });
return defer.promise; if (promised) {
return cb.promise;
}
} }
function setInMultipleCaches(caches, opts, cb) { function setInMultipleCaches(caches, opts, cb) {
opts.options = opts.options || {}; opts.options = opts.options || {};
var promised = false;
if (!cb) {
promised = true;
cb = Promise.defer();
}
async.each(caches, function(cache, next) { async.each(caches, function(cache, next) {
var _isCacheableValue = getIsCacheableValueFunction(cache); var _isCacheableValue = getIsCacheableValueFunction(cache);
@ -102,16 +112,16 @@ var multiCaching = function(caches, options) {
next(); next();
} }
}, function(err, result) { }, function(err, result) {
if (typeof cb === 'object') { if (promised) {
if (err) { return (err) ? cb.reject(err) : cb.resolve(result);
cb.reject(err);
} else { } else {
cb.resolve(result);
}
} else if (typeof cb === 'function') {
cb(err, result); cb(err, result);
} }
}); });
if (promised) {
return cb.promise;
}
} }
/** /**
@ -257,11 +267,7 @@ var multiCaching = function(caches, options) {
options: options options: options
}; };
var defer = Promise.defer(); return setInMultipleCaches(caches, opts, cb);
setInMultipleCaches(caches, opts, cb || defer);
return defer.promise;
}; };
/** /**

Loading…
Cancel
Save