【问题标题】:Conditionally perform an action with redis使用 redis 有条件地执行一个动作
【发布时间】:2021-09-15 05:58:51
【问题描述】:

我想创建一个将键(字符串)作为输入的函数。如果缓存中存在键,则该函数将返回 true,否则它将添加键到缓存并返回 false。我对 redis 很陌生,所以我感谢所有帮助。

const redis = require('redis');
const client = redis.createClient();

const lookup = (key) => {
client.get(key, (err, reply) => {
if(err) return err;
if(reply !== null) return true;
if(reply === null) {
  client.set(key, 1);
  return false;
} 

}) }

const key = 'key';
const doesKeyExist = lookup(key);
console.log(doesKeyExist);

【问题讨论】:

  • 你没有从lookup返回任何东西
  • 是的,我知道,因为我不知道如何在回调之外访问回复

标签: node.js redis node-redis


【解决方案1】:

由于node-redis不支持promise,你需要给你的函数传递一个回调,或者看看如何使用util.promisify

没有util.promisify的解决方案:

const redis = require('redis');
const client = redis.createClient();

const lookup = (key, callback) => {
  client.get(key, (err, reply) => {
    if(err) callback(err, null);
    if(reply !== null) callback(null, true);
    if(reply === null) {
      client.set(key, 1);
      callback(null, false);
    })
}

const key = 'key';
lookup(key, (err, doesKeyExist) => {
  console.log(doesKeyExist);
});

【讨论】:

  • 很抱歉添加了一个额外的问题,但是否可以将函数“lookup()”的调用附加到可以访问的变量(我未定义)?因为我希望外部返回根据查找函数中发生的情况而变化。
  • 我明白你的意思,你能做的最接近的就是使用async/await 语法,因为你需要从lookup 返回一个Promise
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多