0

My use case demands me to call an sql recursively till no rows are returned for which I have written the below code which due to async nature doesn't work as expected.

The piece of code which does this invocation is:

let Response = await getData(userId);

async function getData(userId) {
  console.log("Invoking Get Data Function");
  let arrayOfUserId = [userId];
  let fetchMore = true,
    j = 1;
  let keyWithQoutes = -1;

  return new Promise((resolve, reject) => {
    do {
      console.log(arrayOfUserId, j)
      j++;
      if (arrayOfUserId.length > 0) {
        keyWithQoutes = arrayOfUserId.map((it) => {
          return `'${it}'`;
        });
      }
      const sql = ` Select userId from USER where reportingTo in (${arrayOfUserId})`;
      console.log(' SQL Query ', sql);
      con.query(sql, [], async(error, response) => {
        if (error) {
          fetchMore = false;
          reject(error);
        }
        console.log(
          " Response for ",
          userId,
          response,
          response.length
        );
        if (response.length == 0) {
          fetchMore = false;
          resolve(arrayOfUserId);
        }
        else {
          for (let i = 0; i < response.length; i++) {
            console.log(response[i].userId);
            arrayOfUserId.push(response[i].userId);
          }
        }
      });
    } while (fetchMore);
  });
}
Tokyo
  • 201
  • 1
  • 5
  • 18
  • What dbms are you using? Some allow recursion in the sql. – jakubiszon Dec 31 '20 at 10:36
  • If you want to use callbacks - you should not use a loop. If you want to use async you don't need callbacks. I think you need to learn the difference first. In async function you would normally do `response = await con.query(sql, []);` but I don't even know if the lib you're using allows async calls. – jakubiszon Dec 31 '20 at 10:44
  • i am using mysql [ "mysql": "^2.17.1"] – Tokyo Dec 31 '20 at 12:31
  • npm page of the `mysql` package https://www.npmjs.com/package/mysql github: https://github.com/mysqljs/mysql#readme The above pages do not seem to include `async/await` so I assume the package uses callbacks only. In this case you can promisify the function the way it was done here: https://stackoverflow.com/questions/44004418/node-js-async-await-using-with-mysql – jakubiszon Dec 31 '20 at 13:09

0 Answers0