From b92743fb871ce64e5b8673f0447121b76d62b424 Mon Sep 17 00:00:00 2001 From: Jonathan Date: Mon, 18 Jan 2016 11:33:34 +0100 Subject: [PATCH] Add multi-caching promise support for Wrap --- lib/multi_caching.js | 18 +++++++++++ test/multi_caching.unit.js | 64 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/lib/multi_caching.js b/lib/multi_caching.js index 5b4a90b..73fe35f 100644 --- a/lib/multi_caching.js +++ b/lib/multi_caching.js @@ -145,6 +145,17 @@ var multiCaching = function(caches, options) { }; } + if (!cb) { + cb = Promise.defer(); + var work2 = work; + work = function(cb) { + Promise.resolve().then(work2).then(function(res) { + cb(null, res); + }) + .catch(cb); + }; + } + var hasKey = callbackFiller.has(key); callbackFiller.add(key, {cb: cb, domain: process.domain}); if (hasKey) { return; } @@ -175,6 +186,9 @@ var multiCaching = function(caches, options) { } if (!self._isCacheableValue(data)) { + if (typeof cb === 'object') { + return cb.resolve(data); + } return cb(); } @@ -186,6 +200,10 @@ var multiCaching = function(caches, options) { }); } }); + + if (typeof cb === 'object') { + return cb.promise; + } }; /** diff --git a/test/multi_caching.unit.js b/test/multi_caching.unit.js index 4b81b0c..09da385 100644 --- a/test/multi_caching.unit.js +++ b/test/multi_caching.unit.js @@ -970,6 +970,70 @@ describe("multiCaching", function() { }); }); }); + + describe("using native promises", function() { + beforeEach(function() { + multiCache = multiCaching([memoryCache, memoryCache3]); + }); + + it("should be able to chain with simple promise", function(done) { + multiCache.wrap('key', function() { + return 'OK'; + }) + .then(function(res) { + assert.equal(res, 'OK'); + done(); + }); + }); + + it("should be able to chain with cache function as a promise", function(done) { + multiCache.wrap('key', function() { + return new Promise(function(resolve) { + resolve('OK'); + }); + }) + .then(function(res) { + assert.equal(res, 'OK'); + done(); + }); + }); + + it("should be able to catch errors in cache function as a promise", function(done) { + multiCache.wrap('key', function() { + return new Promise(function(resolve, reject) { + reject('NOK'); + }); + }) + .then(function() { + done(new Error('It should not call then since there is an error in the cache function!')); + }) + .catch(function() { + done(); + }); + }); + + it("should be able to catch a throw in cache function as a promise", function(done) { + multiCache.wrap('key', function() { + throw 'NOK'; + }) + .then(function() { + done(new Error('It should not call then since there is an error in the cache function!')); + }) + .catch(function() { + done(); + }); + }); + + it("should be able to chain with non-cacheable value", function(done) { + multiCache.wrap('key', function() { + return; + }) + .then(function(res) { + assert.equal(res, undefined); + done(); + }); + }); + }); }); context("when instantiated with a non-Array 'caches' arg", function() {