Skip to content
Advertisement

How to connect to mssql server synchronously in node.js

All of the examples for using the mssql client package/tedious driver are for async/callbacks/promises but I’m only developing a microservice that will see limited use and my understanding of asynchronous functions is still a bit fuzzy. Here’s what I have for trying to use async/await :

Report generation class:

    const mssql = require('mssql');
    const events = require('events');
    class reporter {
        constructor(searcher, logger) {
            // Pass in search type and value or log the error of none defined
            this.lg = logger
            if (searcher.type && searcher.content) {
                this.lg.lg("reporter created", 3)
                this.srchType = searcher.type;
                this.srchContent = searcher.content;
            } else {
                this.lg.lg("!MISSING SEARCH PARAMETERS", 0);
                this.err = "!MISSING SEARCH PARAMETERS";
            }
        }
        proc() {
            //DB Connect async
            async () => {
                try {
                    await mssql.connect('mssql://username:password@localhost/database')
                    this.result = await mssql.query`select * from mytable where id = ${this.searcher}`
                } catch (err) {
                    // ... error checks
                }
            }
            return this.result;
        }

    }

Then called:

    //Pass to reporter for resolution
    var report1 = new reporter(searcher, logs);

    report1.proc();

I’m sure this is probably a pretty bad way to accomplish this, so I’m also open to any input on good ways to accomplish the end goal, but I’d still like to know if it’s possible to accomplish synchronously.

Advertisement

Answer

You can’t do it synchronously. Figuring out this async stuff is definitely worth your time and effort.

async / await / promises let you more-or-less fake doing it synchronously

const report1 = new reporter(searcher, logs);
report1.proc()
.then ( result => {
    /* in this function, "result" is what your async function returned */
    /* do res.send() here if you're in express */
} )
.catch ( error => {
    /* your lookup failed */
    /* inform the client of your web service about the failure
     * in an appropriate way. */
} )

And, unwrap the async function in your proc function, like so:

    async proc() {
            try {
                await mssql.connect('mssql://username:password@localhost/database')
                this.result = await mssql.query`select * from mytable where id = ${this.searcher}`
            } catch (err) {
                // ... error checks
            }
        return this.result;
    }

await and .then are analogous.

Advertisement