Answer the question
In order to leave comments, you need to log in
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
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 });
});
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'] });
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question