我有以下缓存存储区:
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,
};
我这样称呼它:
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);
}
但是,当承诺进入呼叫id_to_uuid_cache.get(id, cacheName)
时,它将进入内部承诺链
return getCache(cacheName).then(function(cache) {
return BPromise.resolve(cache.get(id));
});
但一旦上线:
return BPromise.resolve(product_cache);
它跳出了对let uuid = p;
行的承诺
我如何确保在完成承诺之前完成承诺链。
答案 0 :(得分:1)
您的条件不会运行两次。您需要执行以下操作:
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));
由于它返回了一个Promise,因此您似乎也可以将id_touuid_cache.get()
函数束缚起来。那可能会更干净。
答案 1 :(得分:1)
由于您的基础代码不是异步的,因此您甚至根本不应该使用promise:
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 };
,然后按以下方式调用它:
const uuid = use_cache ? id_to_uuid_cache.get(id, cacheName) : null;
if (uuid) {
result.set(id, uuid);
} else {
unknown_ids.push(id);
}