B
B
bagos2015-04-17 18:18:51
Node.js
bagos, 2015-04-17 18:18:51

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?
}

I don't like this option.
getAlarmId(function(res){
  ...
});

you need toto like
id = getAlarmId();in id value from the base

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Shemsedinov, 2015-04-18
@bagos

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

But the best thing is not to constantly pull the base on a timer or on request, but on the contrary, make the main storage place for the value - memory, and reset it to the base on a timer, in a pending mode, and only if changes have occurred. We will need the base only for permanent saving, operations with it are slow and asynchronous, and with memory - fast and synchronous. Therefore, by eliminating access to the database during the processing of HTTP (or other) requests, we dramatically increase performance. But all this is no longer Orthodox REST, but stateful programming. I recommend reading more here: habrahabr.ru/post/204958 and here habrahabr.ru/post/247543

I
Ilya Shatokhin, 2015-04-17
@iShatokhin

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 question

Ask a Question

731 491 924 answers to any question