Javascript - error callback is not defined

Asked

Viewed 421 times

1

I’m running a few asynchronous functions, who receive a callback, this callback gets as parameter a Boolean(true or false). When executing I have the error callback is not defined.

[code]

file - app.js

session.checkip(req.ip, function(result) {
        console.log(result);
    });

file - Session.js

exports.checkip = function(ip, callback) {
  var r = false;
  let connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '***********',
    database: 'website_personal_trainer'
  });

  connection.connect(function(err) {
      if (err) {
        return console.error('error: ' + err.message);
      }

      console.log('Connected to the MySQL server. checkip');
    });

  connection.query('select * from session', function(err, result, fields){
    for (var i in result)
        if (result[i].ip == ip) {
            r = true;
            break;
        }
    connection.end(function(err) {
      if (err) {
        return console.log('error:' + err.message);
      }
      console.log('Close the database connection.');
      callback(r);
    });
  });

[Debuging] When changing the parameter to receive strings, the function performs normally. Can you help me?

[update] - 23/02/2019 The code presented works correctly. After having found an alternative solution for what I wanted to do, I tested this same code again and did not get any error. Therefore, the above error does not have to do with this code.

  • 1

    I don’t think that mistake is in the code you have in the question.

  • The function callback does not exist in the context in which it was called, within another callback. ---> callback(r), in this case, you can correct by redeclaring the variable: var callback = callback just below exports.checkip = function(ip, callback) {

  • @edsonalves failed to notice. Session.checkip is not a callback. Could explain your reasoning pf.

  • You receive a callback in this function and try to call it inside another callback. This other one can not see the received function in form

2 answers

2

I made some adjustments to the code to ensure the callback function call regardless of errors or not, also added a parameter to it to validate errors, and changed the for by a filter.

exports.checkip = function (ip, callback) {

    const connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'Escola171995',
        database: 'website_personal_trainer'
    });

    connection.connect(function (err) {
        if (err) return callback('error:' + err.message, false);
    });

    connection.query('SELECT * FROM session', function (err, result, fields) {

        let sessionIp = result.filter(session => session.ip == ip);

        connection.end(function (err) {
            if (err) return callback('error:' + err.message, false);

            if (sessionIp.length > 0){
                callback(true, 'Close the database connection.');
            }else{
                callback(false, 'Not Close the database connection.');
            }

        });
    });
}

session.checkip(req.ip, function(err, result) {
    if (err) console.log(err);
    console.log(result);
});

I believe these adjustments will help you.

About the Undefined problem in callback, I believe it is because the function was not executed because of the Return call

  • Pedro, another thing that can help is to query the database using Where and solving the data filtering in the database, something like: "SELECT * FROM Session WHERE Session.ip = ?" passing the IP as a query parameter.

  • What was the original problem in the code that motivated the "callback is not defined"?

  • @Sergio the original error is that if I use arguments of type Boolean(i.e., the callback function uses result type Boolean) I have the error callback is not defined. When I use strings to represent booleans(ie true or false) the code runs perfectly.

  • @fabioxd20 I realized that before seeing your answer, you’re absolutely right. A filter would also be a good option. However this query with WHERE was used to improve the code.

  • @Stone occurs what you write does not make sense. The mistake that would be logical is callback is not a function, is said to be undefined That’s another kind of problem.

  • @Sergio basically the idea is the following https://jsfiddle.net/hyuv0eq3/4/, is just because my myFunction in the current case is in a file that is imported. But like I said, switching booleans to strings works. This example of code I showed you works for both, so I understand your doubt.

  • @You’re right, the mistake I made back then wasn’t about that, my mess. Because now I have tested again after having already found an alternative solution and works correctly for all types (including booleans). You can advise me, I do not know how to follow the topic. I should delete?

  • It won’t be because I did, in the.end() Return console.log();?

  • @The most important thing is that we learn to program better and share with others. If you want to give an answer, delete the question or ask abioxd20 to adapt the answer.

  • Exactly! When you gave Return in the function that expected the callback you did not execute the function, I believe this is the reason too

Show 5 more comments

0

It returns the value and is not receiving the value within the for loop. Therefore, when Voce places a string in var r the Calback sends the initial value of the variable and not the value MODIFIED IN FOR LOOP. A SOLUTION:

Connection.query('select * from Session', Function(err, result, Fields){

let count = 0;

let limit =result.length;

for (var i in result)

    if (result[i].ip == ip) {

        r = true;

        break;
    }

  count++;

if(count == limit) {


connection.end(function(err) {
    if (err) {
        return console.log('error:' + err.message);
    }
    console.log('Close the database connection.');
    callback(r);
 });

}

  • "Connetion.end()" only runs after the "for" cycle has ended, so that’s not how it works.

Browser other questions tagged

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