S
S
Sergey Mironov2020-11-14 22:08:23
Node.js
Sergey Mironov, 2020-11-14 22:08:23

How to get variable outside mysql scope in node.js?

var line_last_id = "SELECT MAX(id) FROM table_name"; 

conn.query(line_last_id, function(err, result) {
var last_id = result[0]['MAX(id)']);  			
});

console.log(last_id);


How to get last_id for area conn.query? Inside is displayed, outside is no longer there. Tried via push, doesn't work either

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Mironov, 2020-11-14
@zevem

Decided so

function getLastId(){
return new Promise(function(resolve, reject) {
var line_last_id = "SELECT MAX(id) FROM table_name"; 
conn.query(line_last_id, function(err, result){                                                
resolve(result[0]['MAX(id)']);
})
})
}

getLastId().then((lastid) => console.log(lastid));

V
Vitaly, 2020-11-14
@vshvydky

the result of qwery is asynchronous and is passed to the callback, it’s not in your case, but in general you need to learn js
then promises and async functions, after that it will turn out as you want.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question