0

I'm trying to use sql queries as promises. I can't seem to get it to work:

   query: (sql, args) => {
    if (args) sql = mysql.format(sql, args);
    return new Promise((resolve, reject) => {
      pool.getConnection((err, connection) => {
        if (err) {
          console.log(err);
          reject(Error(err.code));
        }

        connection.query(sql, (err, results) => {
          connection.release(); // always put connection back in pool after last query
          if (err) {
            console.log(err);
            resolve([]);
          }

          resolve(results);
        });
      });
    });
  },

And here is the query itself:

async function dbCall(sql, arg) {
      let data = await db.query(sql, arg);
      console.log(data);
      data = data[0];
      return data;
    }

And here is the pool:

var pool = mysql.createPool({
  host: 'localhost',
  user: 'user',
  password: 'pass',
  database: 'db',
});

What I'm trying to do: I'm trying to have it where it doesn't get hung up on async functions. I want it to return a value throughout a whole async function instead of inside of itself only.

Right now, it isn't working at all. However, when it is I would like row to be defined in my whole function instead of just inside the db.query.

I'm not sure if this makes sense, but if you need more clarification just ask anything.

William
  • 1,175
  • 2
  • 17
  • 32

1 Answers1

1

Well if I understand your questions correctly you're misunderstanding how promises should be handled. Promises make use of a then() function to perform something only after the async request is finsihed.

It reads pretty well in plain English. Perform my async request THEN do something with the data.

Try this:

db.query(userSQL, username).then(res => console.log(res))

Additionally, you could use an async function. This allows use to handle async functions in a similar way to synchronous functions where your code will be executed sequentially without having to worry about chaining and nesting other code inside of then() functions

async function dbCall() {
    let data = await db.query(userSQL, username);
    console.log(data);
}

As a side note. This was super helpful to me when I was first getting into Promises.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

23k
  • 1,596
  • 3
  • 23
  • 52
  • I've updated my query code, but I'm still producing nothing. I tried using `let data = await db.query(userSQL, username); console.log(data);` But it doesn;t produce any results. The console doesn't even return undefined, or anything. So I think it is getting hung up. – William Apr 06 '18 at 22:39
  • Post your updated code – 23k Apr 06 '18 at 22:40
  • I did, it's in OP. – William Apr 06 '18 at 22:40
  • I dont see anything I suggested in your post – 23k Apr 06 '18 at 22:42
  • Sorry thought I updated it. Updated the query. It now goes through, but `row` is undefined. – William Apr 06 '18 at 22:48
  • Nevermind, I got it... well kind of. Now I'm having the same issue as assigning a variable only does it within the promise and will does not do it globally... which is why I tried going the promise route to begin with.... so I am back to square one. – William Apr 06 '18 at 22:50
  • So you want the value that's resolved in the promise to be available globally? – 23k Apr 06 '18 at 23:03
  • More or less yes. I created a separate async function. `async function dbCall(sql, arg) { let data = await db.query(sql, arg); console.log(data); data = data[0]; return data; }` And I'm trying to call it here: `dbCall(userSQL, username); console.log(data);` Basically I want to be able to user that data to compare and check for things. – William Apr 06 '18 at 23:09
  • Please format your code in your post so I can better read what's going on – 23k Apr 06 '18 at 23:10
  • Why can't you just assign a variable to the function `let results = dbCall(..)`? – 23k Apr 06 '18 at 23:11
  • Oh! Well... that should have been obvious, lol. But now I have a different issue: I just did as you said: `let userData = dbCall(userSQL, username); console.log(userData);` and here is the log output: `Promise { }` – William Apr 06 '18 at 23:16
  • try adding the await keyword. `let userData = await dbCall(..)` – 23k Apr 06 '18 at 23:16
  • Not sure if that will work or not, just curious – 23k Apr 06 '18 at 23:18
  • ` let userData = await dbCall(userSQL, username); ^^^^^^ SyntaxError: Unexpected identifier ` – William Apr 06 '18 at 23:19
  • okay so I just set it as a timeout... `setTimeout(() => { console.log(userData); }, 100);` And it worked flawlessly. – William Apr 06 '18 at 23:26
  • right. that's probably not very good way to handle it. can you try doing this before you go with the settimeout method. `let userData = dbCall(..).then(data => data);` – 23k Apr 06 '18 at 23:28
  • Nope that way still returns pending... on a sidenote.. how exactly do I access that data? Because it is `Promise { data {}}` I thought `userData[0]` would have produced to the row data but it turns to undefined. if I did `userData.username` would also return as undefined... but it holes the data correctly. – William Apr 06 '18 at 23:31