R
R
Roman2019-06-09 11:24:15
Node.js
Roman, 2019-06-09 11:24:15

How exactly do I make this (code in the text) Node.js function asynchronous?

Hello. Here is the function from serverMiddleware in Nuxt:

export default function(req, res, next) {

    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'user',
        password: 'secret',
        database: 'db'
    });

    connection.connect();

    connection.query("SELECT * FROM table", function(err, result, fields) {
        if (err) throw err;
        let exp = JSON.stringify(result);
        res.send(exp);
    });

    connection.end();

}

as you can see, it just makes a request to the database and returns JSON.
Can you please tell me exactly how I can make this function asynchronous?
And should I make it asynchronous at all? All the same, after all, you will have to wait for an answer in any way (am I right? Or am I missing something again?)
Then there will be an [asynchronous] request from the browser to it.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2019-06-09
@Robur

You already have everything asynchronous. You just close the connection immediately without waiting for the request to complete.
take out the creation and closing of the connection to the database from the middleware somewhere in the server initialization and you will have everything as it should be.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question