How exactly am I supposed to do this (code in text) function Node.js asynchronous?

Hello. Here is a function of 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.query("SELECT * FROM table", function(err, result, fields) {
 if (err) throw err;
 let exp = JSON.stringify(result);
Res. send(exp);



as you can see, it just makes a query to the database and gives JSON.

Please tell me how exactly can I make this function asynchronous?

And I need it to do async then? Anyway it will have to wait for an answer anyway (I correctly argue? or, again, missing something?)

It will then [async] request from a browser.

Thanks in advance.
March 23rd 20 at 19:43
1 answer
March 23rd 20 at 19:45
You already have everything asynchronous. You just close connexin immediately without waiting for the query execution.

move the creation and closing connexin to the database from the middleware somewhere in the initialization of the server and you will have everything as it should be.
A example where this can be done in Nuxt? In server/index.js? And where is there better to do? - Brett_Jacobi commented on March 23rd 20 at 19:48
//I have Express - Brett_Jacobi commented on March 23rd 20 at 19:51
I'm not familiar with Nuxt, but server/index.js possible fit. Can make where create express server or any other services initialize - Tremaine_Kli commented on March 23rd 20 at 19:54

Find more questions by tags Node.js