From 5dae350582169df0e33b8031e43d4347813cc397 Mon Sep 17 00:00:00 2001 From: Jonathan Date: Wed, 20 Jan 2016 00:09:43 +0100 Subject: [PATCH] Refactor promise usage and return it only if no callback provided --- lib/multi_caching.js | 50 +++++++++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/lib/multi_caching.js b/lib/multi_caching.js index dd552a4..eac6c91 100644 --- a/lib/multi_caching.js +++ b/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); }; /**