Y
Y
Yevhenii K2019-09-06 12:36:05
JavaScript
Yevhenii K, 2019-09-06 12:36:05

Why is only 1 DB query executed after page reload?

When the page is loaded for the first time, after the server starts, both queries are executed, after the page is reloaded, only the first one is executed.
app.js

var connection = require('./lib/db');

global.connection = connection;

db.js
var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    database: 'test',
    user: 'root',
    password: '',
});

connection.connect(function(err) {
    if(err) throw err;

    console.log('Connected');
});

module.exports = connection;

index.js
router.get('/', function (req, res, next) {
    let data = {};
    connection.query("SELECT * FROM hc_posts ORDER BY id DESC LIMIT 10", function (err, result, fields) {
        if (err) throw err;
        data.posts = result;
    });
    connection.query("SELECT COUNT(*) FROM hc_posts", function (err, result, fields) {
        if (err) throw err;
        data.amount = result[0]['COUNT(*)'] + 1;
    });

    res.render('index', { data: data });
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Michael, 2019-09-06
@notiv-nt

Decision:

router.get('/', function (req, res, next) {
    let data = {};

    connection.query("SELECT * FROM hc_posts ORDER BY id DESC LIMIT 10", function (err, result, fields) {
        if (err) throw err;
        data.posts = result;

        connection.query("SELECT COUNT(*) FROM hc_posts", function (err, result, fields) {
            if (err) throw err;

            data.amount = result[0]['COUNT(*)'] + 1;

            res.render('index', { data: data });
        });
    });
});

but it's so so

M
marataziat, 2019-09-06
@marataziat

The matter is that you use asynchronous code with synchronous! That is, the request to the database does not have time to be completed, but the response is already underway! When you do something in asynchronous code, the compiler doesn't wait for the line to complete, it just loops over it and then does what it needs to inside ..then when the request is done! The browser's fetch API has a similar issue, you can use async/await to avoid asynchronous code via .then()!!
It was:

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
  });

It became:
let response = await fetch(`https://api.github.com/users/${name}`);
 let data = await response.json()

Do the same with your code!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question