Click here to Skip to main content
15,394,479 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is ajax returned by connecting to mysql from node.
However, the resulting value is not output.

What is the problem?

What I have tried:

JavaScript
var http = require('http');
var url = require('url');

var db_config = require('mysql.js');

let mysqld = {} // mysql result
app.get('/server', function(req, res){

   let num = req.query.pID;
   let sql = 'select * from wt_serials where id=?';

   let params = [num];
   let conn = db_config.init();

   db_config.connect(conn);

   conn.query(sql, params, function(err, rows, fields){
      mysqld = JSON.stringify(rows);
      console.log('1 '+mysqld); // result is corrent
    });

    console.log('2 '+mysqld);  // result is [object Object]
    rss.json(mysqld);  // empty
}


ajax result is {}
Posted
Updated 19-May-22 22:01pm

1 solution

Given the fact that you're passing a callback function to the query function, it's safe to assume that it's running asynchronously. The data won't be available until the callback function is called.

You'll either need to rewrite your code to use the data inside the callback, or find a way to make the code async using a promise[^].
   
Comments
Chopin2001 20-May-22 5:07am
   
Thanks Richard Deeming

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900