Misunderstanding in scope of function

Asked

Viewed 38 times

1

Hello, I am developing a structure to start developing in Ode, I am beginner so forgive me anything.

indexModel.js

var Model = require('./model.js');

var model = new Model();
var data;

class IndexModel {
    // Função inicial
    constructor() {
    }
    // Data banco
    banco() {
        return model.Query('SELECT * FROM test WHERE id = ?', [2], 'select');
    }
    // Retorne a data;
    data() {
      return data;
    }
}

model js.:

var mysql = require('mysql');
var data;

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "root",
  database: "nodejs",
  timezone: "-3:00"
});

class ModelModel {
    // Função inicial
    constructor() {
        con.connect(function(err) {
          if (err) throw err;
          console.log("Connected!");
        });
    }
    // Retorna o valor da query passada
    Query(query, array, type) {
        con.query(query, array, function (error, results, fields) {
          if (error) throw error;
          switch (type) {
            case 'select':
                data = results;
                break;
            case 'insert':
                data = results.insertId;
                break;
            case 'update':
                data = 'changed ' + results.changedRows + ' rows';
                break;
            case 'delete':
                data = 'deleted ' + results.affectedRows + ' rows';
                break;
            default:
                data = results;
                break;
          }
        });
        return data;
    }
    ReturnQuer(result) {
        data = result;
        console.log('aqui'+data);
    }
}

I need to receive the date value outside the function, however I always receive 'Undefined', within the function I am receiving everything correctly, I wonder if there is a way to receive the result of the query Return, or if I am doing something wrong.

NOTE: I removed 'use Strict' and module.Exports because for some reason I can’t add it in the stackoverflow text tool as code.

  • Enter the complete code of your module. Only with this bit is it difficult to identify the error.

  • Okay, I added the other parts (:

  • Leonardo, your problem is that .Query gives an asynchronous answer. Take a look at these other questions/answers I indicated above. Solve the same type of problem.

  • I understand, but you do not give me these solutions, I would like something to wait for the return of it, but unfortunately it seems that there is no solution at the moment.

No answers

Browser other questions tagged

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