简体   繁体   中英

Trying to make function that returns mysql 'SELECT * FROM' results, ended up returning undefined

I'm trying to make a function that returns an array of stats from SQL 'SELECT * FROM', when I don't use a function to return it, it works, but I can't use that array outside of 'function(err, results)'

con.query(`SELECT * FROM MemberPeniz WHERE memberId = '${memberID}'`, function(err, results) {
            if(err) {
                throw err;
            }
            console.log(results)
        })

I tried this:

function checkTimeoutMEMBERid(memberID) {
        con.query(`SELECT * FROM MemberPeniz WHERE memberId = '${memberID}'`, function(err, results) {
            if(err) {
                throw err;
            }
            return results
        })

    }
    const result = checkTimeoutMEMBERid(message.author.id);
    console.log(result)

but as I say it returns undefined no matter what id I pass in

This is because, you are returning results to callback which will not return to caller function. You can update function as,

function checkTimeoutMEMBERid(memberId) {
return new Promise((resolve, reject) =>{
    con.query(`SELECT * FROM MemberPeniz WHERE memberId = ?`,[memberId], (err, results) => {
        if(err) {
            return reject(err)
        }
        resolve(results)
    })
  })
}
checkTimeoutMEMBERid(message.author.id)
.then(result =>
{
console.log(result)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM