Reputation: 8641
I have the following cache store:
const BPromise = require('bluebird');
const LRU = require('lru-cache');
const product_cache = new LRU(5000);
function getCache(cacheName) {
switch (cacheName) {
case 'product_cache':
return BPromise.resolve(product_cache);
default:
return BPromise.resolve(new LRU(5000));
}
}
function set(id, uuid, cacheName) {
return getCache(cacheName).then(function(cache) {
return BPromise.resolve(cache.set(id,uuid));
});
}
function get(id, cacheName) {
return getCache(cacheName).then(function(cache) {
return BPromise.resolve(cache.get(id));
});
}
module.exports = {
set: set,
get: get,
};
I'm calling it as follows:
let p = new BPromise(function(resolve, reject){
if (use_cache) {
return resolve(id_to_uuid_cache.get(id, cacheName));
} else {
return resolve(null);
}
});
let uuid = p;
if (uuid) {
result.set(id, uuid);
} else {
unknown_ids.push(id);
}
however when the promise enters the call id_to_uuid_cache.get(id, cacheName)
it enters the inner promise chain
return getCache(cacheName).then(function(cache) {
return BPromise.resolve(cache.get(id));
});
but once it hits the line:
return BPromise.resolve(product_cache);
it jumps out of the promise to line let uuid = p;
how can I ensure I complete the promise chain before moving out to the promise.
Upvotes: 0
Views: 60
Reputation: 51916
Seeing as your underlying code is not asynchronous, you shouldn't even be using a promise at all:
const LRU = require('lru-cache');
const product_cache = new LRU(5000);
function getCache(cacheName) {
switch (cacheName) {
case 'product_cache':
return product_cache;
default:
return new LRU(5000);
}
}
function set(id, uuid, cacheName) {
const cache = getCache(cacheName);
return cache.set(id, uuid);
}
function get(id, cacheName) {
const cache = getCache(cacheName);
return cache.get(id);
}
module.exports = { set, get };
and then call it as follows:
const uuid = use_cache ? id_to_uuid_cache.get(id, cacheName) : null;
if (uuid) {
result.set(id, uuid);
} else {
unknown_ids.push(id);
}
Upvotes: 1
Reputation: 158
Your condition is not going to run twice. You need to do something like:
let p = new BPromise(function(resolve, reject){
if (use_cache) {
resolve(id_to_uuid_cache.get(id, cacheName));
} else {
reject(id);
}
});
p.then(resolvedValue => {
result.set(resolvedValue);
}).catch(id => unknown_ids.push(id));
It looks like you could also just chain off of the id_touuid_cache.get()
function since it returns a promise. That would probably be cleaner.
Upvotes: 1