How to return the value of a query to the database in another javascript file?

Asked

Viewed 298 times

1

I’m making an application where I need to query a database and return the value to another javascript file, only for some reason it’s not exporting anything to the other file when doing exports.result = resultado; , follows the code below:

//Conexao com BD MySQL
const mysql = require('mysql');

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'username',
    password: '123456',
    database: 'database'
});

connection.connect(function (err) {
    if (err) {
        console.error('error connecting: ' + err.stack);
        return;
    }
    console.log('connected as id ' + connection.threadId);
});

connection.query('SELECT * from informacoes;', function (err, rows, fields) {
    if (!err) {
        var resultado = rows;
        exports.result = resultado;
    } else {
        console.log('Erro ao realizar a consulta');
    }
});
  • what mistake? you did not put in your question

  • I edited the question... When I check the file I should export, it is empty

1 answer

1


Cannot assign values to variable exports asynchronously, which is what you’re trying to do. You need the value you want to export to be obtained synchronously.

As most of the operations done in a db are done by asynchronous functions, there is no way to export anything that results from these operations through the exports of the js.

What you can do is export a function that accepts a callback as an argument and execute its query within that function. For example:

//Conexao com BD MySQL
const mysql = require('mysql');

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'username',
    password: '123456',
    database: 'database'
});

connection.connect(function (err) {
    if (err) {
        console.error('error connecting: ' + err.stack);
        return;
    }
    console.log('connected as id ' + connection.threadId);
});

exports.query = function (cb) {
    connection.query('SELECT * from informacoes;', function (err, rows, fields) {
        if (!err) {
            var resultado = rows;
            cb(null, resultado);
        } else {
            console.log('Erro ao realizar a consulta');
            cb(err);
        }
    });
}

Another way would be to use an IIFE (Immediately Invoked Function Expression) along with async, but this will only work with ES7 onwards. Another detail is that the mysql driver you are using does not work with Promises, so you would have to create a function that encapsulates the query and returns a file. That way your code would look like this:

function queryWithPromise (query) {
    return new Promise((resolve, reject) => {
        connection.query(query, function (err, rows, fields) {
            if (err) return reject(err)

            resolve(rows)
        })
    }
}

module.exports = (async function () {
    const resultado = await queryWithPromise('SELECT * from informacoes;')
    return resultado
})()

Then you use await when importing the file:

let informacoes
(async function () {
    informacoes = await require('./caminho/pro/arquivo.js')
})()
  • Ok, but how could I get the return value in a variable from another JS file?

  • That way you can already get the value. You just need to perform the function that was exported and pass a callback that will do whatever you want to do with the value. In the case of ES7 you can use an immediately run asynchronous function. I will add an answer explaining this method.

  • All right, I got it done, thank you very much! You saved me a lot here, vlw

Browser other questions tagged

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