1

I am making a website where i need to import data from database and use it later in program. But when i am using npm package mysql i can't find any way to import result of query outside function for later use. Here is an example of my code.
Function with that i get data from database:

    let output;
        dba.query('SELECT * FROM `movies-web`.movies;',(err, rows) => {
            if(err) {
                throw err;
            } else {
                output = rows;
            }
        });

And in code i use it like this:

res.write(output);

But the variable output return undefined.

I am solving this problem for longer than month, i browsed so many pages, questions here on stackoverflow and i can't find working solution.

michal_cz17
  • 13
  • 1
  • 2
  • you're responding with the output before the query has been executed. You should move `res.write` inside the callback – ajmnz Nov 21 '21 at 15:18

1 Answers1

0

You can't write code like that, I suggest you read about callback documents and learn how to use asynchronous in the node is

Your code should write like that:

dba.query('SELECT * FROM `movies-web`.movies;',(err, rows) => {
            if(err) {
                throw err;
            } else {
                res.write(rows)
            }
        });

P.S:

A better scenario for use callback:

const http = require('http');

function executeQuery(next) {
  dba.query('SELECT * FROM `movies-web`.movies;',(err, rows) => {
    if(err) {
      console.error(err);
      next(err);
      return
    }
    
    next(null, rows);
  });
}

const server = http.createServer(function (req, res) {
  executeQuery(function (error, output) {
    if (error) {
      res.writeHead(400);
      res.end(error.message);
      return;
    }

    res.writeHead(200);
    res.end(JSON.stringify(output));
  });
});

server.listen(8080);
Pooya
  • 2,968
  • 2
  • 12
  • 18