This question already has answers here:
How do I access previous promise results in a .then() chain?
                            
                                (17个答案)
                            
                    
                3年前关闭。
        

    

我曾经这样编码,最终发现自己陷入了回调地狱。

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


但是,当我这样做时:

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


我无法再访问res1。在每个返回上传递参数感觉很脏。

有什么优雅的解决方案吗?

最佳答案

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

08-07 23:18