NodeJS: getting and passing variables

I'm having trouble calculating the "transfer" variables (I know this is not the right term, I will explain), given the asynchronous nature of node.js.

Please take a look at the following:

connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if(err) { throw err; } var solution = rows[0].solution; }); res.render('index', { title: solution }); 

As you can imagine, I get a reference error, solution is not defined . This is because res.render is executed before a solution is received from the mysql server.

How can I render a page after defining a solution? I know this is really small and stupid and really located in the very heart of the node, but please help me understand.

+4
source share
1 answer

The second connection.query parameter is your callback, which is triggered when the database returns. Why not put the string res.render inside the callback? Thus, the visualization function is not called until your data is ready.

 connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if(err) throw err; var solution = rows[0].solution; res.render('index', { title: solution }); }); 

Callbacks can be a little tricky when you first start with Node. You just need to come up with steps that should happen and that are asynchronous. From there, you just need to make sure your callbacks allow you to continue the process.

+6
source

Source: https://habr.com/ru/post/1433421/


All Articles