-1

guys. I cant resolve some prolem with js callback return. So, we have next func:

     //Функция получения контакт листа пользователя
        function get_contact_list(data) {
            //Берем ID пользователя, который к нам пытается обратиться исходя из SESSION_ID
            conn.query('SELECT id FROM users WHERE session_id="' + data['auth'] + '" LIMIT 1;', function(err, res) {
                if (err) {
                    console.log(err);
                }
                //Разбираем результат
                res.fetchAll(function(err, row) {
                    if (err) {
                        console.log(err);
                    }
                    //А теперь, собсна, выбираем контакты
                    conn.query('SELECT u.id, u.sname, u.fname, u.nick FROM users as u LEFT JOIN contacts AS c ON c.dep_id = u.id WHERE owner_id =' + row[0].id + ';', function(err, res) {
                        if (err) {
                            console.log(err);
                        }
                        //Разбираем результат
                        res.fetchAll(function(err, row) {
                            if (err) {
                                console.log(err);
                            }
                            //TAKE row HEREOF
                            NEED_OUT = row;
                        });
                    });
                });
            });
            return NEED_OUT;
        }

I need return variable row from 2-lvl callback, but if i create global var or write "row" in global object, it's not working. Help me pls! Thank you!

vladimirg
  • 72
  • 1
  • 7
  • Althought it's a different context, you should read my answer here, to learn about synchronous and asynchronous code: http://stackoverflow.com/a/14220323/218196. You have to make `get_contact_list` accept a callback and pass the result of the DB query. – Felix Kling Apr 27 '13 at 13:03
  • I think promises would help the readability of this code. – Paul Grime Apr 27 '13 at 13:05
  • Please determine where you want to the row object to be saved. You can always pass a callback function as a parameter and call it by passing the row value as a parameter to it – tusharmath Apr 27 '13 at 13:09

1 Answers1

3

I believe you didn't get the concept of async code right. Because you example is way to long, here some pseudo code that shows you in which order async code will work.

// Timestamp: 0
function foo(input, cb) {
    // Timestamp: 2
    doSomeThingAsync(input, (result) {
        // Timestamp: 5
        result = transformResultSync(result);
        cb(result);
    });
    // Timestamp: 3
}
// Timestamp: 1
foo('bar', function(result) {
    // Timestamp: 6
    console.log(result);
});
// Timestamp: 4

I hope it helps a little bit.

TheHippo
  • 61,720
  • 15
  • 75
  • 100