node.js MySQL package is inserting multiple values into table when it should only be inserting one.
I’m using node.js MySQL package to INSERT values with JavaScript. Every time I run the query, multiple values are inserted into the table, as if the query was ran multiple times. I believe maybe it has to do with asynchronous nature of JavaScript and promises.
import { getData} from 'backend/MySQL_DB_Connection';
$w.onReady(function () {
getData()
.then(function (results) {
console.log(results);
//$w("#html1").postMessage(results);
})
.catch(function (err) {
console.log("Promise rejection error: " + err);
})
});
export function getData() {
return new Promise(function (resolve, reject) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'ec2-xxxxxxxxe-1.amazonaws.com',
user: 'xxxxx',
password: 'xxxxx',
database: 'xxxxoli_webform'
});
connection.connect(function (err) {
var sql = "INSERT INTO webform (Name) VALUES ('test1')";
connection.query(sql, function (err, result1) {
if (result1 === undefined) {
reject(new Error("Error result is undefined"));
} else {
resolve(result1)
}
});
connection.end();
});
});