我是Javascript的新手。我正在尝试使用promise和async等待获取所有行及其父行
这是我的代码
const e = require('express')
const mysql2 = require('mysql2')
const pool = mysql2.createPool({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'dreamselling',
waitForConnections: false,
connectionLimit: 10,
queueLimit: 0
})
let levels=[];
const getLevel = (id,levels) => {
return new Promise((resolve, reject) => {
let sql = `select id,memberName,parent_id from member_table where id=${id}`;
pool.getConnection((error, connection) => {
connection.query(sql, (err, rows) => {
if (rows && rows[0].parent_id != null) {
// console.log(rows[0]);
levels.push((rows[0]))
getLevel(rows[0].parent_id,levels)
} else {
pool.end()
}
})
})
})
}
async function myfunc() {
let a = await getLevel(7)
console.log(levels);
// console.log('level',a);
}
myfunc()
我可以用console.log查看行(rows[0](但无法从函数返回我需要关于这个的帮助
按照@robertklep的建议,尝试使用async await
此外,请确保使用事先准备好的声明:
const e = require('express');
const mysql2 = require('mysql2');
const pool = mysql2.createPool({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'dreamselling',
waitForConnections: false,
connectionLimit: 10,
queueLimit: 0,
});
let levels = [];
const getLevel = async (id, levels) => {
const promisePool = pool.promise();
const [rows, fields] = await promisePool.query(
'select id,memberName,parent_id from member_table where id = ?',
[id]
);
if (rows && rows[0].parent_id !== null) {
levels.push(rows[0]);
getLevel(rows[0].parent_id, levels);
} else {
pool.end();
}
};
function myfunc() {
getLevel(7);
console.log(levels);
}
myfunc();