If function return does not recognize true, only false

Asked

Viewed 290 times

1

I have this code below, which was to if the function returns true, it runs if. But it only executes if if I change if to false, that is, by putting "if(!linkAlreadySent)" instead of "if(linkAlreadySent)". Does anyone know how to point out the problem?

var link = "http://www.google.com";

function linkAlreadySent(link) {
    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');
            return true;
        } else {
            console.log('Retornando false, o link não existe');
            return false;
        }
    });
}

if(linkAlreadySent(link)) {
  console.log('Entrou no if');
}
  • 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.

  • 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

  • 2

    John, the function linkAlreadySent is not returning anything. Who is returning true or false is the callback function of the method mysql.handle.query. For the function linkAlreadySent 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?

  • Hmmm, maybe that’s right @user140828. But I’m not very familiar with this, can give me a light?

1 answer

1


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();
  • Now I understand what you meant. NA mysql-libmysqlclient API each function has two versions one is synchronous and the other is asynchronous, the difference being that the synchronous functions have the suffix Sync in front of the functions. Seen this you are right my code does not work. I am withdrawing my answer.

  • I understand perfectly, thank you!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.