Mysql node function
I want to make a call to the mysql server with node and store data into a fucntion:
async function getData(uri){ let data = await esisteMysql(uri); console.log(data); } function esisteMysql(uri) { connection.query(`select * from data where url = '${uri}'`, function (error, row) { if(error) throw error; else { if(row && row.length){ console.log('FOUND'); //console.log(row); return row; }else{ console.log('NOT FOUND'); return row = null; } } }) }
It doesn’t work, it returns an undefined. I can log data only if I print it in esisteMysql with console.log(row);
Your esisteMysql()
needs to produce a promise in order to work with await
. It might look something like:
async function getData(uri) { let data = await esisteMysql(uri); console.log(data); } function esisteMysql(uri) { return new Promise(function(resolve, reject) { connection.query(`select * from data where url = '${uri}'`, function (error, row) { if (error) { reject(error); } else { resolve(row); } }) } }
See https://javascript.info/async for more.