Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
http server respnd with an output from an async function

I want my http respond script to respond with data from my SQL server. So I can use AJAX to update HTML with data from my SQL server. And I cant find a way to do this. I'm just learning about async and I have a feeling that if I can save the output of my async function to a global var then it will work. Any help would save my headache.

My simple Listen script is:

var test = "hello!"

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write(test);
  res.end();
}).listen(8080); 

and my sql code is:

const util = require('util');
var mysql = require('mysql');

var con = mysql.createConnection({
    host: "XXXXX",
    user: "XXXXX",
    password: "XXXXX",
    database: "XXX"
  });

var DBresult=null;

function getdb(){
  const query = util.promisify(con.query).bind(con);
  (async () => {
    try {
      const rows = await query('SELECT * FROM mylist');
      DBresult=rows;
     
    } finally {
      con.end();
    }
  })()
}

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Do NOT use any globals or shared, higher scoped variables for your asynchronous result in a server. Never do that. That is an anti-pattern for good reason because that can create intermittent concurrency problems because more than one request can be in process at the same time on your server so these would cause conflicting access to those variables, creating intermittent, very-hard-to-debug problems. I repeat again, NEVER.

You didn't describe an exact situation you are trying to write code for, but here's an example.

Instead, you use the result inside the context that it arrives from your asynchronous call. If you can use await, that generally makes the coding cleaner.

Here's a simple example:

const con = mysql.createConnection({
    host: "XXXXX",
    user: "XXXXX",
    password: "XXXXX",
    database: "XXX"
});

const query = util.promisify(con.query).bind(con);

http.createServer(async function(req, res) {
    if (req.path === "/query" && req.method === "GET") {
        try {
            const rows = await query('SELECT * FROM mylist');
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify(rows));
        } catch(e) {
            console.log(e);
            res.statusCode = 500;
            res.end();
        }
    } else {
        // some other respone
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.write("hello");
        res.end();
    }
}).listen(8080);

Things to note here:

  1. Checking both path and method before handling the request.
  2. Making callback function async so it can use await.
  3. Making sure any promise rejection from await is caught by try/catch and an error response is sent if there's an error.
  4. Sending result as JSON and setting appropriate content-type.
  5. You may be using the plain http module as a learning experience, but you will very quickly find that using the simple Express framework will save you lots of programming time and make things lots easier.
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda