简体   繁体   中英

Await is the Only Async function : API NODE

I'm unable the below snippet of code. I tried calling an async function, but I'm getting an error as shown below.I'm trying to connect to Microsoft SQL Server. Please review the code, and please inform me what is the with the these code snippet.

**SyntaxError: await is only valid in async function**


var express = require('express');
var router = express.Router();
var sql = require('mssql');

async function connectDB(){

 const pool = new sql.ConnectionPool(global.config.sqlConfig);
     try {
         await pool.connect();
         console.log('Connected to DATABASE');
         return pool;
     }
     catch(err){
         console.log('conn failure');
         return err;
     }
};

async function executeQuery(req, res){    
 const DB = await connectDB(); 
 try{
     var result = await DB.request()
     .query(req).then(function () {
        console.log("QUERY PASSED");
        console.log(result.recordset);
        return result.recordset;
     });

 }
 catch(err){
     console.log("ERROR QUERYing DATABASE");
     return err;
 }
 finally{
      DB.close();
 }

 };

router.get('/login', function (req, res) {   
   var strquery = "select fUserPwd from tblUser where fUserID ='ADMIN'";
    console.log(strquery);
   const result = await executeQuery(strquery, res); 
   res.send(result);     

});

module.exports = router; 

I wanted the recordset to be get displayed on opening the link. Is there any way to resolve this issue?

Problem is in this route.

   router.get('/login',async function (req, res) {   
       var strquery = "select fUserPwd from tblUser where fUserID ='ADMIN'";
        console.log(strquery);
       const result = await executeQuery(strquery, res); 
       res.send(result);     

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM