Answer the question
In order to leave comments, you need to log in
How to get the result of a function with nested nodejs functions?
I know that this is not very welcome, but a global variable is set, it is immutable, I need to get the value from the database and write it to this variable in order to use this variable in further requests of the restful application.
function getAlarmId(callback){
connection.query('SELECT id from alarm where type=1', function(err, rows, result) {
rows.forEach(function (alarm) {
callback(alarm.id);
});
return 2;
});
return 1; // получаю только это значение, как в него передать callback?
}
getAlarmId(function(res){
...
});
id = getAlarmId();
in id value from the base
Answer the question
In order to leave comments, you need to log in
That global variables are bad is nothing more than conventional wisdom, often culminating in a religious sentiment. Adherents can not rationally explain why it is impossible. All the arguments that this confuses the code do not stand up to criticism, because there are many examples when the introduction of a global variable, on the contrary, simplifies the code and makes it more understandable. In addition, a bunch of everything you need is in the global scope: console, setInterval, clearImmediate, parseInt, Infinity, Math, decodeURI, all built-in classes, and much more. For browsers also: document and window. And even require is a global variable, apologists for some reason do not require writing var require = require('require'); How so, not in order, require is global. The heresy of globality lies at the very heart of dependency injection. Actually, not all of these identifiers are really global, and there may be contexts in Node.js, the same require will not be visible, but this is not about that now. And that the use of global variables can produce both useful and harmful results. In your case, you can do it like this:
// Инициализация глобальной области
global.model = { // задаем значеня по умолчанию
alarmId: null // можно поставить, например, -1 или в зависимости от задачи
};
// Функция получения
function getAlarmId(callback) {
connection.query('SELECT id from alarm where type=1', function(err, rows, result) {
if (!err && rows.length === 1) {
var row = rows[0];
model.alarmId = row[Object.keys(row)[0]];
}
if (callback) callback();
});
}
// Можем теперь вызвать при старте приложения, обычно без колбека
getAlarmId();
// А по ходу исполнения можем вызывать его с колбеком, так и без колбека
getAlarmId(function() {
console.dir(model);
)};
// Или обновлять по таймеру
setInterval(getAlarmId, 5000);
A global variable is really a bad idea, since you still want to execute asynchronous code synchronously :) If the motives of the first requirement are clear, then the second is not.
Synchronization can be provided to you only by your DB adapter (which I personally doubt). You can use Promise/await/yield generators , but the code will still remain asynchronous even though you write it in one line.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question