0

I am new to redis, at the moment using the redis client npm package to interact with it. I have a function which attempts to return a value from redis like so:

The key/val pair is like : foo/true

function getVal(key: string, field: string) {
    // updates value for that field
        return client.hget(key, field, function (hashGetError: any, result: any) {
            if (hashGetError) {
                // do something
            } else {
                return new Promise((resolve) => {
                    console.log("fetch result is: " + result); << here I can see a value i.e "true"
                    resolve(result);
                })
            }
    
        });
}

the calling code looks like this

let bar = getVal("key", "foo");
console.log(bar); << this is always returning false?

Any pointers are appreciated :)

Harry
  • 3,031
  • 7
  • 42
  • 67
  • `getVal` is just a wrapper on [`hget`](https://stackoverflow.com/a/10584943/6243352) so it's not going to return anything different from `hget`. As you see, the callback from the asynchronous `hget` is needed to produce a result so you'll need to use a promise to chain from that; currently the promise isn't returned anywhere useful and not to the caller of `getVal` as you may think. – ggorlen Jul 10 '20 at 16:41
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ggorlen Jul 10 '20 at 16:42
  • so this should work? let bar = await getVal("key", "foo"); or did i misunderstand? – Harry Jul 10 '20 at 16:49
  • No because the promise isn't returned to the caller scope. The promise should be on the outside of the `hget` and returned to the caller, then the promise fires the `hget` call which has the callback that `resolve`s the promise. Alternately, you could pass a callback into `getVal` and make that the callback to `hget`, but this doesn't seem any better than simply calling `hget` directly from the caller. – ggorlen Jul 10 '20 at 16:52
  • ahh! of course you are correct. That has fixed it for me. Actually it is wrapped as the client.hget call lives in a seperate module and i just reference the calling function via an import – Harry Jul 10 '20 at 17:02

0 Answers0