jwen
jwen

Reputation: 79

Redis is outputting true instead of the desired value

I have nodejs running and I want to call this function:

function name(id) {
  var x = rclient.get(id, function(err, reply) {
    return reply;
  });
  return x;
}

however when I try to get the output of the function with console.log(name(1)) the output is true, instead of the value stored on the redis server. this seems like a simple thing to fix, however, it has me stumped.

Upvotes: 1

Views: 391

Answers (1)

Isolated
Isolated

Reputation: 2453

Well you're using callbacks so the return value inside your callback function won't be returned to x.

Try this (depending on your redis client, I've assumed you use node-redis):


function name(id) {
  return new Promise((resolve, reject) => {
    rclient.get(id, function (err, reply) {
      if (err) {
        return reject(err);
      }

      resolve(reply);
    });
  });
}

// call with
name(1).then((value) => console.log(value)).catch((err) => console.log(err));

// better yet (inside async function)
async main() {
  const value = await name(1);
}

Or, do yourself a favour and use handy-redis (https://www.npmjs.com/package/handy-redis):


async function name(id) {
  return rclient.get(id);
}

// call with the same as above

Essentially, you're getting slightly confused with async/sync calls. The fact x resolves to true is likely the implementation of the .get method, and not the callback.

instead of the value stored on the redis server. this seems like a simple thing to fix, however, it has me stumped.

I felt like you when I first started with Node.js, it's odd compared to most languages, however, you'll soon find it more natural (especially with async/await syntax)

Upvotes: 1

Related Questions