Callback connect.query

async function view_department() {
  let department = await inquirer.prompt(department_questions);

  get_query("department", "name", department.choices, function (data) {
    get_query("role", "department_id", data[0].id, function (data) {
      let table = [];
      for (var i = 0; i < data.length; i++) {
        get_query("employee", "role_id", data[i].id, function (data) {
          console.log(data[0]);
          table.push(data[0]); 
          //when I console.table(table) here it does print the table I need,
          //but it doing that for how ever many time the loop run
        });
      }
      console.table(table); //table is empty, it's not waiting for the code above to finish
    });
  });
}
async function get_query(table, data, value, callback) {
  connection.query(
    `SELECT * FROM ${table} WHERE ${data} = ?`,
    [value],
    (err, res) => {
      if (err) callback(err);
      callback(res);
    }
  );
}

I’m trying to get data from one table and use it to get data from another table, but I just don’t understand how callback work and/or how to implement them.

Answer

It’s not a good idea to mix async/await or promise with callbacks. The main reason why promise was introduced is to avoid nesting of callbacks With promise this same problem can be solved like

async function get_query(table, data, value) {
  return new Promise((resolve, reject) => {
    connection.query(
    `SELECT * FROM ${table} WHERE ${data} = ?`,
    [value],
    (err, res) => {
      if (err) reject(err);
      resolve(res);
    }
  );
  })
}

Now get_query can be used as

const firstResult = await get_query("department", "name", department.choices)

await get_query("role", "department_id", firstResult[0].id)

Hope I have explained it properly, my idea is to avoid callbacks.

Leave a Reply

Your email address will not be published. Required fields are marked *