0

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".

2
  • Did you try adding a return keyword before each method call? Ex. function1("arg1", function(err, rows){ return client.query(sql1, function(err,rows){ return 1;} ); ? Commented Jan 19, 2015 at 16:32
  • @CyberneticTwerkGuruOrc Returning won't do anything, since it's asynchronous. Commented Jan 19, 2015 at 16:33

1 Answer 1

3

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.


Sign up to request clarification or add additional context in comments.

5 Comments

I've updated the question. Can you pls. comment if this is what you meant ?
@KayaToast yes, pretty much exactly that. Even tho I don't know why you call the callback with null as first argument, the principle is exactly right.
Thanks. The null was a way to highlight that there is no err
Tried it and it works ... but I needed to pass that extra function to both outer and inner functions. Thanks! ... and now, I dunno why, but this phrase is ringing in my mind "functions in javascript are first class objects !" :-)
@KayaToast great :-) To further get into this topic, you might want to research a little about the such called "Promises" respectively "Promise objects". That is a very awesome concept to bring this callback-thing on a complete new and even more convenient level!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.