R
R
Roman Hinex2015-06-05 05:38:59
JavaScript
Roman Hinex, 2015-06-05 05:38:59

How to pull a variable outside of a function in JavaScript?

How can I pull data out of the scope of the called function (callback)? Or how can you pull data from a model in Mongoose and use the values ​​later in the code?

var items_list;
db.model('items').find({}, function (err, data) {  items_list = data });
console.log(items_list); // undefined

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Timur Shemsedinov, 2015-06-05
@HiNeX

It just doesn't need to be done. Instead, you need to understand the idea of ​​asynchronous programming. All callbacks are executed not at the place of their declaration, but when data comes to them, therefore, in your code example, it happens first console.log(items_list);and only then items_list = data. And this is good, because there is no waiting for the execution of callbacks, there is no blocking of the execution thread. You can write all the synchronous logic for processing the data received in the callback directly in the callback, and if you need to implement a serial or parallel call of several asynchronous requests (everything related to input / output, access to the database and files, for example), then this can be done in different ways. ways, the most popular of them are the async library and promises. I am using https://github.com/caolan/async For example:

var async = require('async');
var items_list, users_list;
async.parallel([
    function(callback) { // делаем первый запрос к базе
      db.model('items').find({}, function (err, data) {
        items_list = data;
        callback(); // данные получены, возвращаемся
      });
    },
    function(callback) { // параллельно делаем второй запрос к базе
      db.model('users').find({}, function (err, data) {
        users_list = data;
        callback(); // данные получены, возвращаемся
      });
    }
],
function() {
  // когда оба запроса уже завершены, то мы попадаем сюда
  console.dir({ items: items_list, users: users_list });
});

N
Nazar Mokrinsky, 2015-06-05
@nazarpc

The closest analogy to what you want is with Promises.

D
Dmitry Avilov, 2015-06-05
@TheCreator

It is much more convenient (and more correct) to write async in this style.

var async = require('async');
async.auto({
    'Aitems': function(callback) { // делаем первый запрос к базе
      db.model('items').find({}, function (err, data) {
        callback(err, data); // данные получены, возвращаемся
      });
    },
    'Busers': function(callback) { // параллельно делаем второй запрос к базе
      db.model('users').find({}, function (err, data) {
        callback(err, data); // данные получены, возвращаемся
      });
    }
},
function(err, results) {
  if (err){return console.error(err);} // если будут ошибки - их напишем.
  // ошибок нет, нам доступны результаты каждой операции
  console.dir({ items: results['Aitems'], users: results['Busers'] });
});

You have error handling, plus you make sure that your items_list and user_list variables won't be changed somewhere else during request processing. It's not nice to move variables outside of a function that changes them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question