Kaya Toast
Kaya Toast

Reputation: 5493

return value from within several nested callbacks in node

I want to return the value from within nested callbacks. Below is the pseudo code:

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

Here is my attempt to make it work

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;
                            });
                        });
                    });
                });

But I'm unable to figure out how to get function1 to return function2's "rows".

Upvotes: 0

Views: 357

Answers (1)

jAndy
jAndy

Reputation: 235962

You don't and to an extend, you can't. In theory you could pass the value or reference to an upper context and return it, but that only works if every process in between works perfectly synchronous.

So what to do ? Callback is the solution. Instead of relaying on the return value, you pass in an additional function to your outer method and call that function with the desired value.


Upvotes: 3

Related Questions