2

I'm trying to query my mysql database for a value using Async/Await but my constant 'map' always returns undefined, I am not too sure why

const get_map = () =>{
    db.query('SELECT game,game2 FROM battles WHERE player1=? OR player2=?',[result.char,result.char],(err,results)=>{
        if(err){
            return(err)
        }
        if(!results[0]){
            return('No such battle?')
        }
        console.log(results[0])
        return(results[0])
    })
}
const proccessTurn = async ()=>{
    const map = await get_map()
    console.log(map)
    let game = JSON.parse(map.game)
    let game2 = JSON.parse(map.game2)
    const char = result.char
    const playerTurn = game2.turn[0]
}

The console doesn't even log

console.log(results[0])

This line so why does the await function resolve before it actually returns something? Shouldn't it wait for the returns?

Thank you for the help

3
  • Remove {...} from get_map or change it to return db.query(...) and it should work fine. Commented Aug 1, 2021 at 19:22
  • @ulou What is the problem and how does your suggestion solve it? Commented Aug 1, 2021 at 19:23
  • The problem is that he forgot about return, I think it's good enough explanation. Commented Aug 1, 2021 at 19:23

2 Answers 2

3

As the mysql library doesn't support promises, you can use the promisify util function from Node.js like this:

const { promisify } = require('util');

const query = promisify(db.query).bind(db);

const get_map = async () => {
    try {
         const result = await query('SELECT game,game2 FROM battles WHERE player1=? OR player2=?',[result.char,result.char]);
         if(!results[0]){
             return 'No such battle?';
         }
         console.log(results[0])
         return results[0];
    }
    catch(e) {
         return e;
    }
}
const proccessTurn = async ()=>{
    const map = await get_map()
    console.log(map)
    let game = JSON.parse(map.game)
    let game2 = JSON.parse(map.game2)
    const char = result.char
    const playerTurn = game2.turn[0]
}
Sign up to request clarification or add additional context in comments.

6 Comments

Hi, I tried this out but it returns TypeError: Cannot read property 'typeCast' of undefined
It was a mistake in my code I replaced .bind(db.query) with .bind(db). You should use this code rather than reinventing the wheel like the other answer suggests.
@GuerricP Returning a new promise is not re-inventing the wheel, I think. And by creating a new promise you can handle your biz specific edge cases in the same function.
Returning a promise is not reinventing the wheel, returning a promise with our own code is. The Node.js callback signature is a standard, Promise is a standard, that's why promisify exists.
@rauf543 historically Node.js handled asynchronism with a callback taking three parameters: error, data and next. The current trend is to use promises which highly helps write cleaner code, especially with async/await so they provided a native tool: promisify in order to facilitate the migration to the new promises pattern. It just takes a function which takes a Node.js callback as last parameter and transforms it in a function returning a Promise. Wrapping into a Promise with custom code is not advised, as this buit-in solution exists.
|
2

The third parameter to db.query() is a callback. If you're returning anything in callback it's actually returned to the function itself, (db.query in this case). You're not returning anything from get_map(). So return a new promise from get_map like this,

const get_map = () =>{
    return new Promise((resolve, reject) => {
        db.query('SELECT game,game2 FROM battles WHERE player1=? OR player2=?',[result.char,result.char],(err,results)=>{
            if(err){
                reject(err)
            }
            if(!results[0]){
                reject('No such battle?')
            }
            console.log(results[0])
            resolve(results[0])
        }
    });
}
const proccessTurn = async ()=>{
    const map = await get_map()
    console.log(map)
    let game = JSON.parse(map.game)
    let game2 = JSON.parse(map.game2)
    const char = result.char
    const playerTurn = game2.turn[0]
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.