async and await on MySQL call in node js

前端 未结 2 1355
庸人自扰
庸人自扰 2020-12-22 12:03

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 be

2条回答
  •  礼貌的吻别
    2020-12-22 12:52

    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

提交回复
热议问题