The problem is that your return
is within the function of callback
of mysql.handle.query
. The callback function is returning a value, but linkAlreadySent
nay.
Well, actually, linkAlreadySent
is returning undefined
, because every function without an explicit return returns undefined
in JS. undefined
is a "falsy" value, it is treated as false when you use it with condition. So how linkAlreadySent
returns undefined
, and you use this return in if(linkAlreadySent(link))
you never fall inside the if
.
How to deal with the problem?
It’s not as simple as returning the return of mysql.handle.query
. The thread
JS main does not wait for input and output processes to continue running the code. When you query the database, the JS keeps running the function until the end, exits the function, and eventually when the database returns a response, the JS executes the callback function you declared. By now it is too late to return a value for the function linkAlreadySent
, 'Cause she’s done rolling.
The functional approach
You can pass a function to linkAlreadySent
execute when it receives the response from the database. As follows:
var link = "http://www.google.com";
function linkAlreadySent(link, callback) {
mysql.handle.query('SELECT link FROM links WHERE link = ?', [link], function (err, res) {
if(res.length == 1) {
console.log('Retornando true, o link ja existe');
// A função é invocada se você entrar na condição desejada
callback(res);
} else {
console.log('Retornando false, o link não existe');
}
});
}
// Passo o link e uma função anonima como parametros
linkAlreadySent(link, (res) => {
console.log('Entrou no "if"');
});
The procedural approach
With the use of promises
, you can "pause" the function (but not the thread
main) until you get the resolution of promise
. Promise
is basically an object that packs an answer, when you get the resolution of the answer, just unpack it from promise
. We do it with the operator await
.
// Módulo do NodeJS
var util = require('util');
var link = "http://www.google.com";
// Crio uma nova função que retorna promises
var mysqlQuery = util.promisify(mysql.handle.query);
// Funções precisam do modificador async para poderem utilizar await
// Toda função do tipo async retorna resultados empacotados em promises
async function linkAlreadySent(link) {
// Espero pela resposta
var res = await mysqlQuery('SELECT link FROM links WHERE link = ?', [link]);
if (res.length == 1) {
console.log('Retornando true, o link ja existe');
return true;
} else {
console.log('Retornando false, o link não existe');
return false;
}
}
async verificaLink() {
// Novamente, utilizamos await, pois o retorno de linkAlreadySent está empacotado
if (await linkAlreadySent(link)) {
console.log('Entrou no if');
}
}
verificaLink();
I don’t quite understand what you want to do, but here’s the deal
var teste = linkAlreadySent(link)
and gives a console log. on test to see what returns.– LeAndrade
The linkAlreadySent function queries the table to check if the link record already exists in the "link" column. If it exists, it returns true. If not, false. if below will be called if the function returns true
– jvdutra
John, the function
linkAlreadySent
is not returning anything. Who is returningtrue
orfalse
is the callback function of the methodmysql.handle.query
. For the functionlinkAlreadySent
return something, you need to declare that return outside of internal functions. But then you will need to deal with the asynchronism of this code, you are already familiar with it or you need an answer?– Andre
Hmmm, maybe that’s right @user140828. But I’m not very familiar with this, can give me a light?
– jvdutra