Undefined value after returning an array of values from a MySQL query in a different file

旧城冷巷雨未停 提交于 2019-11-28 14:49:46

Use Async/Await with promises. You cannot use the syntax with callback. You have to change your dbConnection.js as below. You have to promisify your callback.

function myQuery(){ 
    return new Promise(function(resolve, reject){
        var array = new Array();
        const sql1 = "SELECT * FROM table1 WHERE active=1";
        con.query(sql1, function (err, result, fields) {
            if (err) throw err;
            array = [];
            for(var i=0; i<result.length; i++) {
                array.push(result[i].active);                        
            }
            console.log(array) //here it prints out the array with its values
            resolve(array);
        });
    })
}

const getData = async ()=> {
    var array= await myQuery();
    return array;       
}
module.exports.getData = getData;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!