summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGraeme Yeates <gyeates@clearpath.ai>2017-08-21 19:57:58 -0400
committerGraeme Yeates <gyeates@clearpath.ai>2017-08-21 19:57:58 -0400
commit139421571d26b458a44f452c46b48230c4277a7a (patch)
tree2d20c7fa6e056933fbfc86a8b16a66f5a03a9bcb
parentfa206affed3a13261c4fb4b314a5bf0df8e50308 (diff)
downloadasync-1465.tar.gz
#1465; don't memoize results that had an error1465
-rw-r--r--lib/memoize.js9
-rw-r--r--mocha_test/memoize.js28
2 files changed, 30 insertions, 7 deletions
diff --git a/lib/memoize.js b/lib/memoize.js
index 27c08bc..9ef871a 100644
--- a/lib/memoize.js
+++ b/lib/memoize.js
@@ -14,6 +14,9 @@ function has(obj, key) {
* function results against, the callback is omitted from the hash and an
* optional hash function can be used.
*
+ * **Note: if the async function errs, the result will not be cached and
+ * subsequent calls will call the wrapped function.**
+ *
* If no hash function is specified, the first argument is used as a hash key,
* which may work reasonably if it is a string or a data type that converts to a
* distinct string. Note that objects and arrays will not behave reasonably.
@@ -63,7 +66,11 @@ export default function memoize(fn, hasher) {
queues[key] = [callback];
_fn.apply(null, args.concat(function(/*args*/) {
var args = slice(arguments);
- memo[key] = args;
+ var err = args[0];
+ // #1465 don't memoize if an error occurred
+ if (!err) {
+ memo[key] = args;
+ }
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
diff --git a/mocha_test/memoize.js b/mocha_test/memoize.js
index 39620dd..df800cf 100644
--- a/mocha_test/memoize.js
+++ b/mocha_test/memoize.js
@@ -100,9 +100,8 @@ describe("memoize", function() {
var fn2 = async.unmemoize(fn);
fn2(1, 2, function(err, result) {
expect(result).to.equal(3);
+ done();
});
-
- done();
});
it('error', function(done) {
@@ -112,8 +111,26 @@ describe("memoize", function() {
};
async.memoize(fn)(1, 2, function (err) {
expect(err).to.equal(testerr);
+ done();
+ });
+ });
+
+ it('should not memoize result if error occurs', function(done) {
+ var testerr = new Error('test');
+ var fn = function (arg1, arg2, callback) {
+ callback(testerr, arg1 + arg2);
+ };
+ var memoized = async.memoize(fn);
+ memoized(1, 2, function (err) {
+ expect(err).to.equal(testerr);
+ testerr = null;
+
+ memoized(5, 6, function (err, result) {
+ expect(err).to.equal(null);
+ expect(result).to.equal(11);
+ done();
+ });
});
- done();
});
it('multiple calls', function(done) {
@@ -134,10 +151,8 @@ describe("memoize", function() {
});
it('custom hash function', function(done) {
- var testerr = new Error('test');
-
var fn = function (arg1, arg2, callback) {
- callback(testerr, arg1 + arg2);
+ callback(null, arg1 + arg2);
};
var fn2 = async.memoize(fn, function () {
return 'custom hash';
@@ -205,4 +220,5 @@ describe("memoize", function() {
done();
});
});
+
});