0

I know this has been answered here already (How do I return the response from an asynchronous call?), but I couldn't find anything that would work with what I need.

I have a basic function reading data from a databse, that's then supposed to return a value depending on the data. This is what it looks like:

function checkcooldown(name, user){
    //gets the row from the sqlite database (returns a promise)
    sql.get(`SELECT * FROM usercooldowns WHERE user = "${user}" AND name = "${name}"`).then((row) => {
        if(!row || row == undefined){return 0} //if the user doesn't have a cooldown, return 0
        else if(row.time <= getcurdate()){//if the cooldown is already over, return 0
            return 0
        }
        else{//if a cooldown exists, return the number of seconds it lasts (currently dummy number)
            return 123
        }
    })
}

I want to call this function in an if statement similar to this

if(await checkcooldown(name, user) > 0){//do something}
else{//add a new cooldown}

This of course doesn't work, since the function returns undefined.

However, none of the solutions I found in the thread above helped me with this, they all ended up using multi-line functions or resolving promises. Is there ANY way to make it compact enough to fit in a simple if statement like I described above?

Thanks for the help ^^

Aci
  • 546
  • 5
  • 22

1 Answers1

0

Why not just use async await syntax if you want to be concise ?

    async function checkcooldown(name, user) {
         try {

         const row = await sql.get(`SELECT * FROM usercooldowns WHERE user = "${user}" AND name = "${name}"`)

         } catch(err) {
          console.log(err)
         }
        if(row.time <= getcurdate()) {
          return 0
         } else {
          return 123
         }
     }
C.Gochev
  • 1,837
  • 11
  • 21