首页 > 解决方案 > 返回的数组具有未定义的值

问题描述

我正在尝试通过 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 的新手,所以我无法正确理解它。我该如何解决这个问题?

标签: node.jsexpressasync-await

解决方案


如果您将调用的函数设为异步,它会返回一些结果吗?

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;
              }
         })

        }

       })
      }

推荐阅读