Answer the question
In order to leave comments, you need to log in
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;
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;
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
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 });
});
});
});
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));
});
let response = await fetch(`https://api.github.com/users/${name}`);
let data = await response.json()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question