Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!