Цепочка обещаний, выходящая при возврате первого обещания - PullRequest
0 голосов
/ 07 января 2019

У меня есть следующее хранилище кеша:

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; как я могу убедиться, что завершил цепочку обещаний, прежде чем перейти к обещанию.

Ответы [ 2 ]

0 голосов
/ 07 января 2019

Поскольку исходный код не асинхронный, вам даже не следует использовать обещание:

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);
}
0 голосов
/ 07 января 2019

Ваше состояние не будет выполняться дважды. Вам нужно сделать что-то вроде:

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

Похоже, вы могли бы просто отключить функцию id_touuid_cache.get(), так как она возвращает обещание. Это, вероятно, будет чище.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...