Browse Source

Refactor promise usage and return it only if no callback provided

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

50
lib/multi_caching.js

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

Loading…
Cancel
Save