1

I am using mysql package from https://www.npmjs.com/package/mysql

So basically I have this function in a file:

module.exports.listGames = (id) => {
  let query = 'SELECT * FROM test';
  if (id) {
    query += 'WHERE userid = ' + connection.escape(id);
  }

  connection.query(query, function(err, results) {
    if (err) {
      throw err;
    }
    console.log(results);
  });
}

and I want to return those results in the json format

so I can call it in another file which is this function:

function sendGames(req, res) {
    const games = db.listGames(req.query.game);
    res.json(games);
}

so my question is, How can I return the results from that query?

2 Answers 2

2

You can either

  1. Use callback
module.exports.listGames = (id, cb) => {
  let query = 'SELECT * FROM test';
  if (id) {
    query += 'WHERE userid = ' + connection.escape(id);
  }

  connection.query(query, function(err, results) {
    if (err) {
      throw err;
    }
    cb(results);
  });
}

module.exports.listGames(12, (results) => {
console.log(results);
})
  1. Use promise
module.exports.listGames = (id) => {
  let query = 'SELECT * FROM test';
  if (id) {
    query += 'WHERE userid = ' + connection.escape(id);
  }
  return new Promise((resolve, reject) => {
    connection.query(query, function(err, results) {
      if (err) {
        throw err;
      }
      resolve(results);
    });
  })

}

module.exports.listGames(12).then(results => console.log(results)

You can encode the response from mysql query to JSON using JSON.stringify.

Sign up to request clarification or add additional context in comments.

2 Comments

Using callback throws me an error saying "callback is not a function", using promise it returns me an empty object. I do not need this line "module.exports.listGames(12).then(results => console.log(results)" as I wanna call the function with a req.query in other file and the console.log(results) was only for debugging purposes. Thank you for your help anyway.
@Nicekor the line module.exports.listGames(12).then(results => console.log(results) is demonstration of how to use listGames function returning a promise object. You can export listGames function and client code can use the function the same way by calling .then(). Also with callback, did you make sure to pass in a correct function?
0
module.exports.listGames = (id) => {
  let query = 'SELECT * FROM test';
  if (id) {
    query += 'WHERE userid = ' + connection.escape(id);
  }

  connection.query(query, function(err, results) {
    if (err) {
      throw err;
    }
    return (results);
  });
}

Declare javascript async function and call the method from here.

async function  sendGames (req, res) {
    var games = await db.listGames(req.query.game);
    res.json(games);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.