node.js - 返回的数组具有未定义的值
问题描述
我正在尝试通过 async/await 返回一个数组:
app.get('/users/article/feed',checkAuthenticated,async (request,response)=>{
try{
function executor(){
let articleArray=[]
const sql="SELECT noOfArticles FROM Articles WHERE id=?"
db.query(sql,[request.user.id], (err,result)=>{
if(err) throw err
let noOfArticles=result[0].noOfArticles
for(let i=1;i<=noOfArticles;i++){
const sql1="SELECT ?? FROM Articles WHERE id=?"
let index='article'+i
db.query(sql1,[index,request.user.id],(err,result)=>{
if(err) throw err
articleArray.push(result[0][index])
if(articleArray.length===noOfArticles){
console.log(articleArray); //here the array is printed as expected
return articleArray;
}
})
}
})
}
const resultArray= await executor();
console.log(resultArray); //here the array is undefined
response.render('viewArticles');
} catch(e){
console.log(e);
}
})
resultArray 始终未定义。我知道这是一个非常古老的问题。我尝试检查 Stack Overflow 中的所有其他答案,但对此我感到很困惑。我是 js 的新手,所以我无法正确理解它。我该如何解决这个问题?
解决方案
如果您将调用的函数设为异步,它会返回一些结果吗?
async function executor(){
let articleArray=[]
const sql="SELECT noOfArticles FROM Articles WHERE id=?"
db.query(sql,[request.user.id], (err,result)=>{
if(err) throw err
let noOfArticles=result[0].noOfArticles
for(let i=1;i<=noOfArticles;i++){
const sql1="SELECT ?? FROM Articles WHERE id=?"
let index='article'+i
db.query(sql1,[index,request.user.id],(err,result)=>{
if(err) throw err
articleArray.push(result[0][index])
if(articleArray.length===noOfArticles){
console.log(articleArray); //here the array is printed as expected
return articleArray;
}
})
}
})
}
推荐阅读
- arrays - 移动数组的索引然后释放它
- python - 从递归函数返回值
- docker - 当多机容器在virtualbox上的ubuntu上共享同一网络时,为什么需要设置“network_mode:host”
- filter - 如何根据条形图轴中的单选切片器仅限制多年?电源 BI
- ios - SwiftUI 为什么 Picker 上的输入不起作用?
- asp.net-mvc-5 - 无法将复选框组数据从视图传递到asp.net mvc中的控制器
- python-3.x - 我使用python制作了一个应用程序我需要在安装时将它添加到命令行
- pandas - “固定回归”上下文中的“回归”一词是什么意思?
- javascript - JQuery 分页不与 div 中的搜索绑定
- c# - 在确保保存所有更改的同时多次增加单个数据库行字段?