-1

I am new to node.js and I want to use promises on my school project. I have found several things online and on stack : Use promise to process MySQL return value in node.js

But I have a question, so far, this is what I have :

router.post('/matchaSearch', function(req, res) {
  var username = session.uniqueID;
  var searcherPackage = {};

  function userAgeCheck(randomParam) {
    return new Promise((resolve, reject) => {
      pool.getConnection((err, connection) => {
        var query = 'SELECT username, age, orientation, sex FROM usersinfo WHERE username != ?';
        connection.query(query, [username], (err, rows, fields) => {
          connection.release();
          return err ? reject(err) : resolve(rows);
        });
      });
    });
  }

  userAgeCheck('username')
    .then((rows) => {
      /*console.log(rows);*/
      searcherPackage = rows;
      console.log(searcherPackage);
      // do stuff
    }).catch((err) => {
      throw err;
    });
});

This is working for me, it returns me everything from the db except me (username). But for me this is not right. Why giving a random param is good ?

So I should give 'username' as param instead of 'randomParam' but if I do it, the query will return me everything instead of everyone except me (username). So I got rid of it and just gave it 'randomParam' and it worked. Can you explain this ? Am I doing this right ? If so, i can keep doing my project. Thank you very much for any help !

Community
  • 1
  • 1
pkerckhove
  • 763
  • 2
  • 10
  • 17
  • There's no purpose served by the `randomParam` in the quoted code. It's your code, isn't it? So why is it there? What was it supposed to do? – T.J. Crowder Jan 03 '17 at 16:56
  • 1
    You need to check the `err` in your `pool.getConnection` callback as well. Or, better yet, use a library like Bluebird and promisify these methods so that you can properly chain them, and let any error automatically reject the returned promise. – cdhowie Jan 03 '17 at 17:02
  • Don't forget that `Promise.promisify` can be used to convert Node.js-style callback methods to promises automatically so you don't have to write your own wrapper. – tadman Jan 03 '17 at 18:24
  • @T.J.Crowder Yes it's my code, the purpose is to get everyone from the database except me (user connected). – pkerckhove Jan 04 '17 at 09:24
  • @pkerckho: It doesn't serve that purpose. `username` seems to be trying to serve that purpose. Again: You haven't used `randomParam` anywhere, so it's utterly pointless in the above. – T.J. Crowder Jan 04 '17 at 09:26
  • @cdhowie How do I use promise.promisify ? Can you please show me an example ? – pkerckhove Jan 04 '17 at 09:27
  • @T.J.Crowder Yes randomParam is pointless but I don't know what param I should give to my function. How should I do it then ? – pkerckhove Jan 04 '17 at 09:34
  • @pkerckho Assuming I didn't screw it up, [like this](http://pastebin.com/Cq31afFd) (where `P` is `require('bluebird')`; some people like to import it as `Promise` tho). Note that any error from the promisified functions will return a rejected promise, so you don't have to check each for errors yourself. Note the use of Bluebirds `.finally()` to release the connection regardless of whether the `query` promise is resolved or rejected. You don't have to explicitly resolve the chain to `rows` since that's the (first) value returned by `query`, which will become the resolved value automatically. – cdhowie Jan 07 '17 at 06:39
  • @pkerckho The important thing to note is that a failure from `getConnection` will cause the promise chain to be rejected, and the code on lines 4-8 won't be run at all. Note how much easier it is to have correct error-handling semantics! In your code, you missed a check against `err` in the `getConnection` callback and so if this function failed, either the whole program will die when you try to do `connection.query`, or the returned promise will simply never be resolved. – cdhowie Jan 07 '17 at 06:42

1 Answers1

1

When you call userAgeCheck (userAgeCheck('username')) you pass one argument: A string literal containing the word "username". This gets assigned to randomParam which you then never user rendering it pointless.


You define a variable at the top of your script: var username = session.uniqueID;

When you make the query you pass the value of the username variable as the placeholder value for username != ?.

This is the value of session.uniqueId since it reads the username variable from the wider scope.

Consequently you get back all the results except those where the username is the username in session.uniqueId.


If you rename randomParam to username, then you have a new, local variable called username with the value "username".

Consequently you get back all the results except those where the username is the username is literally username.


If you want to pass the username as the argument then you need to change userAgeCheck('username') to userAgeCheck(username). i.e. replace the string literal with a variable name.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thank you for your answer, so what you are saying is : my [username] in my connection.query as the value of my var username = session.uniqueID at the top of my code ? So when i declare the function `function userAgeCheck(randomParam)` Should I give it any parameter ? Why should I do it and which one ? – pkerckhove Jan 04 '17 at 09:28
  • @pkerckho — If you aren't going to use a parameter, then don't define one in the argument list and don't pass it one when you call the function. If you are going to use it, then use the same name everywhere and pass the *variable* you want to pass instead of the string literal. – Quentin Jan 04 '17 at 09:43
  • ok I get it, thank you for your help ! I'm going to create a dozen if tiny function without any parameters and get all the data from my db put those into objects and then create a last function with my objects as parameters. I think it's the right idea ! Thanks man ! – pkerckhove Jan 04 '17 at 09:54