0

I used to code like this, and eventually found myself in a callback hell.

 Redis.get("boo", (res1) => {
      Redis.get(res1, (res2) => {
          console.log(res1);
          console.log(res2);
      });
 });

Howeever, when I do it like this:

Redis.getAsync("boo)
.then(res1 => {
    return Redis.getAsync(res1);
})
.then(res2 => {
    console.log(res1) // undefined
});

I cannot access res1 any longer. Passing parameters on each return feels dirty.

Any elegant solutions to this issue?

Aris
  • 2,978
  • 5
  • 22
  • 31
  • Another (dirty) solution would be to declare `res1` in the scope of the whole function. Based on how closure work, I doubt there is a cleaner way to do this. – DrakaSAN Aug 31 '16 at 10:23
  • @DrakaSAN: Very dirty indeed. Don't do that. – Bergi Aug 31 '16 at 10:48

2 Answers2

1
Redis.getAsync("boo")
.then(res1 => {
    return Redis.getAsync(res1).then(res2 => ({res1, res2}));
})
.then(({res1, res2}) => {
    console.log(res1, res2);
});
Maxx
  • 1,740
  • 10
  • 17
0

This is not officially supported but...

What about using aync/await if you are feeling adventurous and happy to use babel.

async function foo() {
  const res1 = await Redis.getAsync("boo")
  const res2 = await Redis.getAsync(res1)
}
alex
  • 5,467
  • 4
  • 33
  • 43