J
J
jeruthadam2017-09-03 02:33:05
Redis
jeruthadam, 2017-09-03 02:33:05

Why does redis return true and not data?

I use radish in conjunction with Noda. The logic is this - the radish returns data to the URL request if it is stored in it, if not, then an axios request is made, the data is returned and stored in the radish itself, in order to use it further. The below code doesn't work, it just returns true. Where did the error creep in?

const cat = axios('http://localhost:3001/cat')
    .then((response) => {
      return response.data
    })
    .catch(error => error)

    const dog = client.get('http://localhost:3002/dog', function (error, dog) {
      if (error) { throw error }
      if (dog) {
        return JSON.parse(dog)
      } else {
        axios('http://localhost:3002/dog')
        .then((response) => {
          return response.data
          client.set('http://localhost:3002/dog', JSON.stringify(response.data), function (error) {
            if (error) { throw error }
          })
        })
        .catch(error => error)
      }
    })

    Promise.all([cat, dog])
    .then((pets) => {
      console.log(pets)
      const cats = pets[0]
      const dogs = pets[1]
      res.json({
        results: {
          cats,
          dogs
        }
      })
    })
    .catch((err) => {
      res.json({
        error: err
      })
    })

UPD. I ran a test, printed it to the console, it const test = client.get('test')also returned true ! In redis-cli it returns the phrase as expected. So the problem might be somewhere else? First day with radishes, please help.
UPD #2. Checking in redis-cli get "http://localhost:3002/dog", I saw that the data is already in the redis! Those. client.set worked. Why doesn't client.get work? Can I use const and return a value? Is this the problem? How to rewrite? Nothing comes to mind.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rail Khusnutdinov, 2017-09-03
@jeruthadam

The previous answer is correct, I will only add that if you want to use promises, you need to include the bluebird library:

const redis = require('redis');
const bluebird = require('bluebird');
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

and all functions use with Async at the end:
const dog = client.getAsync('http://localhost:3002/dog').then((dog) => {
   // ...
});

Then you can usePromise.all

A
Alexander, 2017-09-03
@boratsagdiev

const dog = client.get('http://localhost:3002/dog', function (error, dog) {
      if (error) { throw error }
      if (dog) {
        return JSON.parse(dog)
      }

Here it returns not a promise, and then you try to expand it through Promise.all, look in this direction.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question