2

i am new in Javascript. I am trying to get all row and their parent rows with promise and async await

here is my code

const e = require('express')
const mysql2 = require('mysql2')


const pool = mysql2.createPool({
  host: '127.0.0.1',
  user: 'root',
  password: '',
  database: 'dreamselling',
  waitForConnections: false,
  connectionLimit: 10,
  queueLimit: 0
})

let levels=[];
const getLevel = (id,levels) => {
  return new Promise((resolve, reject) => {
    let sql = `select id,memberName,parent_id from member_table where id=${id}`;
    pool.getConnection((error, connection) => {
      connection.query(sql, (err, rows) => {
        if (rows && rows[0].parent_id != null) {
          // console.log(rows[0]);
          levels.push((rows[0]))
          getLevel(rows[0].parent_id,levels)

        } else {
          pool.end()
        }
      })
    })
  })

}

async function myfunc() {
  let a = await getLevel(7)
  console.log(levels);
  // console.log('level',a);
}
myfunc()

i can see the rows with console.log(rows[0]) but cannot return from the function i need help about this

1
  • Why not use MySQL2's promise wrapper so you can use async/await for your queries? That would at least help you get out of callback-hell. Commented Aug 13, 2022 at 6:57

1 Answer 1

1

Try to use async await as suggested by @robertklep.
Also, make sure that you use a prepared statement:

const e = require('express');
const mysql2 = require('mysql2');

const pool = mysql2.createPool({
  host: '127.0.0.1',
  user: 'root',
  password: '',
  database: 'dreamselling',
  waitForConnections: false,
  connectionLimit: 10,
  queueLimit: 0,
});

let levels = [];

const getLevel = async (id, levels) => {
  const promisePool = pool.promise();
  const [rows, fields] = await promisePool.query(
    'select id,memberName,parent_id from member_table where id = ?',
    [id]
  );
  if (rows && rows[0].parent_id !== null) {
    levels.push(rows[0]);
    getLevel(rows[0].parent_id, levels);
  } else {
    pool.end();
  }
};

function myfunc() {
  getLevel(7);
  console.log(levels);
}

myfunc();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.