0

all I'm pretty new to node and I just learned about the async and await function offered in javascript. I'm trying to implement this method in the code snippet attached below. From my understanding, the database response should first print out to the console and then the "done", but I can't get it to work. Any help would be greatly appreciated.

Please also try to explain what you did to fix it, because I want to understand what I'm doing wrong.

var mysql = require("mysql");
const cTable = require('console.table');

var connection = mysql.createConnection({
    host: "localhost",
    port: 8889,
    user: "root",
    password: "root",
    database: "testDB"
})

connection.connect((err, fields) => {
    if (err) {
        return console.log(err.code);
    }
});

var displayDB = async () => {
    connection.query('SELECT * FROM products', (err, resp) => {
        if (err) {
            return console.log(err.code);
        } else {
            table = [];
            resp.forEach((product) => {
                obj = {
                    'Product ID': product.productID,
                    'Category': product.category,
                    'Price': product.price,
                    'Stock': product.stockQuantity
                }
                table.push(obj)
            })
            console.table(table)
            connection.end()
        }
    })
}

var test = async () => {
    var x = await displayDB()
    console.log('done')
}
test()
2
  • 2
    This isn't going to work unless connection.query returns a promise. I haven't looked in a while, but I don't think the MySQL node module does. So you would need to wrap that in a promise and return the promise from the function. Commented Jul 23, 2018 at 7:32
  • 1
    @MarkMeyer — It wouldn't work even if connection.query did return a promise, since the return value of connection.query is ignored inside displayDB. Commented Jul 23, 2018 at 7:34

2 Answers 2

3

You need to return a promise from the async function displayDB if you want to use the await keyword in test, you need to learn how promises work first. Pseudo code :

var displayDB = () => {
    return new Promise((resolve,reject)=>{
        connection.query('SELECT * FROM products', (err, resp) => {
            if (err) {
                reject(err)
            } else {
                const table = [];
                resp.forEach((product) => {
                    obj = {
                    'Product ID': product.productID,
                    'Category': product.category,
                    'Price': product.price,
                    'Stock': product.stockQuantity
                    }
                    table.push(obj)
                })
                resolve(table)
            }
        })
    })
}


var test = async () => {
   try{
    console.table(await displayDB())
    }catch(e){
        console.log(e)
    }
    connection.end()
}
test()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Sign up to request clarification or add additional context in comments.

2 Comments

You need to return a promise from an async function not really. The async function is not doing anything here, it could be a regular function. You don't have to return a promise from an async function as it does so itself.
to exploit the await keyword you need to resolve a promise in this example. It's all about context. The promise returns a result here, table.
1

You have no return statement in your displayDB function.

Normally this would cause a function to return undefined, but because you declared it async, it causes it to return a Promise that is immediately resolved.

If you want it to wait until the database query is complete, then you need to explicitly return a new Promise which you resolve when you are ready (i.e. after you have called connection.end()).

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.