I'm new to learning Node.js, so I'm still getting used to asynchronous programming and callbacks. I'm trying to query a MS SQL Server database and return the recordset to display in my view.
The mssql query is working correctly when printed to console.log. My problem is not knowing how to properly return the data.
Here is my mssql query:
var config = require('../../db/config');
async function getJobList(activeJD) {
const sql = require('mssql')
let sqlResult = '';
try {
await sql.connect(config)
const result = await sql.query(`select top 10 [jobid], [title] from OrgJobs where ActiveJD = ${activeJD}`);
console.log(result); // working correctly
sqlResult = result;
} catch (err) {
// ... error checks
}
return sqlResult;
}
module.exports = getJobList;
Using express, I'm trying to have my route call this sql query and pass it's result to my view. Here is my route code:
const express = require('express');
//....
const app = express();
//....
app.get('/jds', (req, res) => {
const getJobList = require("../models/jds/list");
let jobList = getJobList(0);
res.render('jds/index', {
title: appName + ' | Job Descriptions',
header: 'Active Job Descriptions',
data: jobList
});
})
The recordset from getJobList() isn't being returned to jobList. I've read around and I believe this is because getJobList is asynchronous and jobList is being called before getJobList has returned it's value, right? If so, I believe I need to add a callback, but I'm not sure how to implement that into what I already have. Any advice is greatly appreciated!
An async
method will always return a Promise . That means that jobList
is a Promise .
let jobList = getJobList(0);
You can either use the await
syntax to "unpack" and get sqlResult
from the promise (you would need to make your callback method async
to do this), or simply use .then
to get the return value from your promise (ie: sqlResult
):
app.get('/jds', (req, res) => {
const getJobList = require("../models/jds/list");
const jobList = getJobList(0); // jobList is a promise
jobList.then(result => { // result is sqlResult
res.render('jds/index', {
title: appName + ' | Job Descriptions',
header: 'Active Job Descriptions',
data: 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.