Decrease code Nodejs

Asked

Viewed 34 times

1

Hi, I’m developing a nodejs system with the express. However I’m facing something I don’t know yet how to solve, I need a code of mine to return result of a bank query:

query = 'SELECT id FROM usuarios WHERE login = ? AND senha = ?';
    array = [POST.login, POST.senha];

    // Adicione a query com scape(?) e os respectivos valores em um array simples
    connection.query(query, array, function (error, results, fields) {
        return results;
    });

It works correctly, but only works within the route, because when used as a function to save lines of code, it does not return the value requested.

I also tried to use the rendering inside the function via app.use(Function (req, res, next) {}); but it didn’t work as I expected and it’s also not what I need.

I basically need:

router.get('/', function(req, res, next) {
    data = funcaoX();
    console.log(data);
});

router.get('/bla', function(req, res, next) {
    data = funcaoX();
    console.log(data);
});

And that in both cases date has the same value, coming from a query, not to write twice the same content.

Excuse me anything, I’m starting in nodejs.

  • 1

    Hello Leonardo! Take a look at the question I indicated above. Basically you have to create a function and then export it to use require or import in other files and invoke that function.

  • Hello Sergio, maybe I’m getting confused, I’m already using require for functionX(); it’s getting init.funcaoX();. But I still don’t understand how to use it with then, rather than init.funcaoX(); I should use it in what way ?

  • 1

    Take a look here: https://answall.com/q/140814/129

  • 1

    Thank you (: I got it

  • Good! Excellent!

No answers

Browser other questions tagged

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