【发布时间】:2020-09-15 07:41:24
【问题描述】:
我正在尝试通过 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 的新手,所以我无法正确理解它。我该如何解决这个问题?
【问题讨论】:
-
executor正在使用基于回调的 API 并且不返回 Promise。db.query是否有基于 Promise 的替代方案?
标签: node.js express async-await