return 来自节点中多个嵌套回调的值

return value from within several nested callbacks in node

我想 return 嵌套回调中的值。下面是伪代码:

dataSetFinal = function1()
within function1
    database is queried to get dataSet1
    call function2, using dataSet1 as arguments
        within function2
        query database to get dataSet2
        return dataSet2
    return dataSet2

这是我尝试让它发挥作用的尝试

dataSetFinal = function1("arg1", function(err, rows){
                    client.query(sql1, function(err,rows){
                        function2(rows[0].userId, function(err, rows){
                            client.query(sql2, function(err, rows){
                                return rows;
                            });
                        });
                    });
                });

但我无法弄清楚如何将函数 1 转换为 return 函数 2 的 "rows"。

你不知道,在某种程度上,你不能。从理论上讲,您可以将值或引用传递给上层上下文并 return 它,但这只有在两者之间的每个进程都完全同步时才有效。

那怎么办?回调是解决方案。您无需依赖 return 值,而是将一个附加函数传递给外部方法并使用所需的值调用该函数。