簡體   English   中英

Node.js mssql 返回記錄集

[英]Node.js mssql return recordset

我是學習 Node.js 的新手,所以我仍然習慣於異步編程和回調。 我正在嘗試查詢 MS SQL Server 數據庫並返回記錄集以顯示在我的視圖中。

mssql 查詢在打印到 console.log 時工作正常。 我的問題是不知道如何正確返回數據。

這是我的 mssql 查詢:

    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;

使用 express,我試圖讓我的路由調用這個 sql 查詢並將它的結果傳遞給我的視圖。 這是我的路線代碼:

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

})

getJobList() 中的記錄集沒有返回到 jobList。 我已經閱讀並相信這是因為 getJobList 是異步的,並且在 getJobList 返回它的值之前正在調用 jobList ,對嗎? 如果是這樣,我相信我需要添加一個回調,但我不確定如何將它實現到我已經擁有的。 任何意見是極大的贊賞!

async方法將始終返回Promise 這意味着jobList是一個Promise

let jobList = getJobList(0);

您可以使用await語法來“解壓”,並得到sqlResult自許(你需要讓你的回調方法async做到這一點),或簡單地使用.then從你的承諾得到返回值(即: 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
      });
    });  
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM