How to return a result value from a async function in node.js with mysql?

Member

by dedrick , in category: MySQL , 2 months ago

How to return a result value from a async function in node.js with mysql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 2 months ago

@dedrick 

To return a result value from an async function in Node.js with MySQL, you can follow these steps:

  1. Use the mysql package to connect to your MySQL database:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'my_database'
});

connection.connect();


  1. Create an async function that performs a query to the database:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
async function getData() {
  return new Promise((resolve, reject) => {
    connection.query('SELECT * FROM my_table', (error, results) => {
      if (error) {
        reject(error);
      } else {
        resolve(results);
      }
    });
  });
}


  1. Call the async function and handle the returned result:
1
2
3
4
5
6
7
8
getData()
  .then((result) => {
    console.log(result);
    // Do something with the result value
  })
  .catch((error) => {
    console.error(error);
  });


By following these steps, you can return a result value from an async function in Node.js with MySQL.