N
N
narem2019-09-14 13:43:10
JavaScript
narem, 2019-09-14 13:43:10

How to make a push from a query into the created array?

Inside the query method, new elements are assigned, but if you output an array outside, it is empty. What should I do to fill it up too?

const express = require('express'),
  app = express(),
  mysql = require('mysql'),
  connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'pcnumber'
  }),
  port = 3000,
  path = require('path'),
  bodyParser = require('body-parser');
let searchbd = '',
  admins = [];

app.set('views', path.join(__dirname, '/pages'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));

connection.connect((err) => {
  if(err){
    return console.log('Ошибка соединения с базой');
  }
  
  console.log('Подключение к базе успешно');
});

connection.query('SELECT name FROM admin',(error, result, fields) => {
  for(var i = 0; i < result.length; i++){
    admins.push(result[i].name);
    console.log(admins);
  }
  console.log(admins);
});


app.get('/pcnumber',(request, response) => {
  response.render('pcnumber');
});

connection.end();

app.listen(port,(err) => {
  if(err){
    return console.log('Ошибка при запуске сервера');
  }
  
  console.log(`Сервер запущен, порт ${port}`);
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2019-09-14
@Stalker_RED

It's not empty, it's full.
But it was filled only during the execution of the query, and if you display its contents BEFORE THIS, then yes, it was initially empty.
What to do - learn to write asynchronously .

C
coderisimo, 2019-09-14
@coderisimo

If you try to access admins before connection.query completes, you get an empty array because admins is still empty when admins is accessed.
how your code is executed :
console.log(1);
connection.query begins ..... (it is asynchronous)
console.log(2); connection.query. hasn't finished yet....
outputting console.log(admins); it is empty because connection.query. hasn't finished yet....
outputs console.log(3); connection.query. hasn't finished yet.... it
prints "query is finished!" - connection.query completed
console.log(admins) - will return received data - connection.query completed and admins filled with data

console.log(1);
connection.query('SELECT name FROM admin',(error, result, fields) => {
  for(var i = 0; i < result.length; i++){
    admins.push(result[i].name);
  
  }
  console.log('query is finished!');
  console.log(admins); // здесь данные доступны
});
console.log(2);
console.log(admins); // здесь данные еще НЕ доступны
console.log(3);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question