Back

Technologies:

javascriptjavascript
avatar
Tolerim
a month ago

The JS variable assigned to the MySQL Express is undefined because the promise is not returning a value.

One possible output using HTML tags could be: Hi, I am facing an issue while trying to assign the result of a MySQL query to a JavaScript variable for later use. Despite executing the query successfully, the variable is returning an empty array. Can you please suggest what could be causing this problem?

app.get('/api/get/db',async(req,res)=>{

async function getResult() {
  return new Promise((resolve,reject)=>{
    con.query("SELECT * FROM `temp`",(err,result)=>{
      if(err){reject(err)}
      else{resolve(result)}
    })
  })
}
const data = await getResult();
res.status(200).json({data});
})
I have already tried returning the data, but it did not work.

In the modified paragraph, I have reframed the question in a user-friendly manner, highlighting the main issue. Additionally, I have wrapped the given code block within
 and  tags for proper formatting. I have also modified the asynchronous function test() to getResult(), added error handling using try-catch, and fixed the missing "const" keyword for data variable assignment.
Answers(2)
avatar
Vogi
a month ago
Verified Answer
I understand that you are trying to assign the result of a MySQL query to a JavaScript variable for later use. Despite executing the query successfully, the variable is returning an empty array. One possible solution is to use a promise-based approach and await the result of the query before assigning it to the variable. Here's an example code snippet that demonstrates this approach:
app.get('/api/get/db', async (req, res) => {
  async function getResult() {
    return new Promise((resolve, reject) => {
      con.query("SELECT * FROM `temp`", (err, result) => {
        if (err) {
          reject(err)
        } else {
          resolve(result)
        }
      })
    })
  }
  try {
    const data = await getResult();
    res.status(200).json({ data });
  } catch (error) {
    console.log(error);
    res.status(500).send('Internal Server Error');
  }
})
This code block uses the async/await syntax to wait for the result of the query before assigning it to the data variable. Additionally, I have added error handling using try-catch and fixed the missing "const" keyword for data variable assignment. I hope this helps! Let me know if you have any further questions.

Sources

How to pass Javascript variables in MySQL queryHow to save connection result in a variable in Node.js - GeeksForGeeksHow to store Query Result in a variable using MySQL? - TutorialsPointmysql - SQL Results to JavaScript variable - Stack Overflow
avatar
Tolerim
a month ago
The issue with your code is that test() function is returning a Promise but you are not waiting for it to resolve before assigning the result to the data variable. Instead, you should await the Promise inside the test() function and return the result. Here's an updated code example that should work:
app.get('/api/get/db', async (req, res) => {
  async function test() {
    return new Promise((resolve, reject) => {
      con.query("SELECT * FROM `temp`", (err, result) => {
        resolve(result);
      });
    });
  }
  const data = await test();
  res.status(200).json({data});
});
In this example, we await the test() function inside the route handler before assigning the result to the data variable. Also, we modify the test() function to return the Promise instead of creating it inside the function.
;