在这里,我需要主索引文件中的sql为数据库添加种子,并检查sql查询是否返回
// require sql connection from main index
const connection = require('./index');
async function tow() {
let arr = [];
let one = await connection.query("Select name FROM department", (err, res) => {
if (err) throw err;
// console.log(res);
console.log('1'arr);
for (let i = 0; i < res.length; i++) {
// pushing to the array here
arr.push(res[i].name);
}
console.log('2',arr);
});
console.log('3',arr);
return one;
}
// I want this function to return array with the pushed elements
tow();
您需要返回arr。同样,您将promise样式与异步的回调样式混合在一起,可以选择一种,但不能混合。尝试这样的事情。
如果connection.query返回一个promise:
async function tow() {
let arr = [];
let one = await connection.query("Select name FROM department").then(res => {
// console.log(res);
console.log('1', arr);
for (let i = 0; i < res.length; i++) {
// pushing to the array here
arr.push(res[i].name);
}
console.log('2',arr);
return arr; // need to return arr
},
err => console.error(err));
console.log('3',arr);
return one;
}
tow().then(res => console.log('result', res));
在您的情况下,如果connection.query
希望有回调函数,则可以将回调转换为类似的Promise。
function tow() {
return new Promise((resolve, reject) => {
let arr = [];
connection.query("Select name FROM department", (err, res) => {
if (err) reject();
// console.log(res);
console.log('1', arr);
for (let i = 0; i < res.length; i++) {
// pushing to the array here
arr.push(res[i].name);
}
console.log('2',arr);
resolve(arr);
});
})
}
// I want this function to return array with the pushed elements
tow().then(res => console.log('result', res));
这是一个代码沙箱
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句