Geoff
Geoff

Reputation: 309

NodeJS SQL Server data pull isn't waiting for promise completion

I am rewriting an ASPX application using Node. Part of this application is pulling data from a table in SQL Server. I am doing this using async functions to try and force the data to be pulled prior to continuing on. It is essential that I have the data before the next step. However, when it returns from the await the response is null.

const getUserGroups = async (user) => {
    let qry = `Select role from [xxxxx] where LOWER(yyyyy)='${user.toLowerCase()}'`;
    let groups = await dataQuery.Select(qry, dbList.MCAIntranet)
    console.log("Groups: ", groups); //This is undefined
    return groups;
    // })
}

Here is the Select function:

const Select = async (query, database) => {
    // console.log(config[database]
    sql.connect(config[database], (err) => {
        if (err) console.log(err);
        let request = new sql.Request();
        request.query(query, (err, recordset) => {
            console.log(recordset)//displays correct data
            if (err) {
                console.log(err);
                return null
            }
            return recordset;
        })
    });
}

I am using the mssql module, but since I am fairly new to Node I am uncertain where my mistake lies.

Thanks in advance for looking at this.

Upvotes: 0

Views: 915

Answers (2)

derpirscher
derpirscher

Reputation: 17400

In you current code, you don't return anything from your Select function. Espectially you are not wrapping your sql code in promise.

You say, you are using the mssql package. This already supports async/await, so you should use the apropriate async calls instead of callbacks.

const Select = async (query, database) => {
   try {
     await sql.connect(config[database]);
     let request =  new sql.Request();
     let recordset = await request.query(query);
     return recordset;
   } catch (e) {
     console.log(e);
     return null;
   }
}

Furthermore you should read about parameterized queries, because currently your code is quite unsafe, ie it is vulnerable to SQL injections and invalid syntax errors.

Upvotes: 1

Firmino Changani
Firmino Changani

Reputation: 959

You can either wrap your implementation with a Promise object, or return Promise.resolve(data);, and return Promise.reject(err):

const Select = async (query, database) => {
  return new Promise((resolve, reject) => {
    // console.log(config[database]
    sql.connect(config[database], (err) => {
        if (err) reject(err);
        let request = new sql.Request();
        
        request.query(query, (err, recordset) => {
            console.log(recordset)//displays correct data
            if (err) {
                console.log(err);
                reject(err);
            }
            resolve(recordset);
        })
    });
  });
}

Upvotes: 0

Related Questions