gpt4 book ai didi

javascript - Promise Chain 在第一个 Promise 返回时退出

转载 作者:行者123 更新时间:2023-12-01 01:22:57 26 4
gpt4 key购买 nike

我有以下缓存存储:

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);
}

但是,当 Promise 进入调用 id_to_uuid_cache.get(id, cacheName) 时,它会进入内部 Promise 链

返回 getCache(cacheName).then(function(cache) {
返回 BPromise.resolve(cache.get(id));
});

但是一旦到达终点线:

返回 BPromise.resolve(product_cache);

它跳出了 Promise 行 let uuid = p;
我怎样才能确保在转向 promise 之前完成 promise 链。

最佳答案

由于您的底层代码不是异步的,您甚至根本不应该使用 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);
}

关于javascript - Promise Chain 在第一个 Promise 返回时退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54080070/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com