I have a problem… I wanted to return “A” but The result was “B” I don’t know what to do Please help me
my code:
async function getID(){ let sql = 'SELECT * from id' connection.query(sql, (err, rows) => { if (err) throw err; console.log(rows) return "A" // return rows }) return "B" } let list = getCredit(); list.then(console.log); console.log(list)
My results
[2022/06/13 21:34:29.548] Promise { 'B' } [2022/06/13 21:34:29.549] B
Advertisement
Answer
You are mixing here callback with promises. To reach what you want, wrap your function in a promise:
function getID(){ return new Promise((resolve, reject) => { let sql = 'SELECT * from id' connection.query(sql, (err, rows) => { if (err){ reject(err) }else{ resolve(rows); } }) }) } let list = getCredit(); list.then(console.log); console.log(list)