有条件地使用redis执行操作

Conditionally perform an action with redis

我想创建一个将键(字符串)作为输入的函数。如果密钥存在于缓存中,函数将 return 为真,否则它将把密钥添加到缓存中,并且 return 为假。我是 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);

因为node-redis不支持promises,你需要给你的函数传递一个回调,或者看看如何使用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);
});