1
1
1Bogdan12020-01-12 12:42:55
JavaScript
1Bogdan1, 2020-01-12 12:42:55

How to get value from function callback?

How to get a value outside of a function?
The output inside the function shows the desired result, but outside is already undefined.

connection.connect();
connection.query('SELECT house_name FROM appartament WHERE street = ? AND house_number = ? AND house_name != ?',
            ['Степана Разина', 2, ''],
            function (error, results, fields) {
                if (error) throw error;
                result.house_name = results[0].house_name;
                console.log(result.house_name); //Выводит нужный результат
        });
connection.end();
    
console.log(result.house_name); //undefined

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pashenka, 2020-01-12
@1Bogdan1

For example, a callback function:

connection.connect();
connection.query('SELECT house_name FROM appartament WHERE street = ? AND house_number = ? AND house_name != ?',
            ['Степана Разина', 2, ''],
            function (error, results, fields) {
                if (error) throw error;
                result = results[0].house_name;
                callback(result);
        });
connection.end();

function callback(data) {
  console.log(data);
  // делаем дела с data
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question