0

Im struggling with this promise

Im working with database calls (db) , so I have delays in my calls. And I cant seem to make calls to this functions await.

async function userExists(id) {
    db.query("SELECT * from users where tg_id=" + id).then(res => {
        if (res[0] === undefined) {
            console.log("we register the user")
            db.query("INSERT INTO users (tg_id, balance) VALUES ('" + id + "','100')").then(res => {
                return new Promise(resolve => {
                    resolve(true)
                })
            }).catch(err => {
                console.log(err)
            })
        } else if (res[0]) {
            console.log("It was already registered")
            return new Promise(resolve => {
                resolve(false)
            })
        }
    }).catch(err => {
        console.log(err)
    })
}

This is the call, where res is always undefined

bot.command('balance', (ctx) => {
    let myId = ctx.update.message.from.id
    var existsStatus = ""
   userExists(myId).then(res => {
       console.log(res) //always undefined
   })
})
mouchin777
  • 1,428
  • 1
  • 31
  • 59
  • 1
    `return db.query(...).then(res => { if (...) return db.query(...).then(() => true); else { return false; } })` – deceze Jun 05 '20 at 14:15
  • `res` is always undefined because your function doesn't return anything, so when it finishes, the promise that it created implicitly is fulfilled with `undefined`. Nothing in your function uses `await` to wait for the promises being created with in it. There's almost never any need to use promises directly in an `async` function. Instead: https://pastebin.com/XSc2W4uT Also, [let me introduce you to my friend Bobby...](https://bobby-tables.com/) – T.J. Crowder Jun 05 '20 at 14:15

0 Answers0