SQL 查询递归异步问题

时间:2020-12-31 10:34:18

标签: javascript node.js

我的用例要求我递归调用 sql,直到没有返回任何行,为此我编写了以下代码,但由于异步性质无法按预期工作。

执行此调用的一段代码是:

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);
  });
}

0 个答案:

没有答案