I'm using the mysql NPM library with Node.JS and I'm trying to query a database and have the function return a Promise instead of requiring a callback. Here's what I've tried:
index.js:
var result = await asyncQuery.main(connection, "SELECT * FROM tbl WHERE id = ?", "1234567890") asyncQuery.js:
var colors = require('colors') module.exports = { main: function(con, q, vars) { return new Promise((resolve, reject) => { if (!vars) { con.query(q, function (err, result) { if (err) { console.log(colors.red(err.stack)) return reject(err); } resolve(result) }) } else { con.query(q, vars, function (err, result) { if (err) { console.log(colors.red(err.stack)) return reject(err); } resolve(result) }) } }) } } This works fine if no vars/args are passed (?), but once a ? is used, I get an error:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1 If I were to run a regular query, with a callback, this would work perfectly fine. There's something wrong with asyncQuery.js, but I'm not sure what the issue is.
Does anyone have a fix for this code, or an easier way to achieve my goal? I've heard of the Promise MySQL Library, but I'm not sure if it supports Promise and callback queries. If it does, let me know and I'll give it a shot.
NodeJS Version: 9.1.0
NPM Version: 5.5.1
NPM's MySQL Library Version: 2.15.0