简体   繁体   中英

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.

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.

Kind of an updated answer that continues off of O. Jones' answer. The current version of Node.js (v15+) has support for top-level await, meaning you can run it all sequentially.

import mssql from 'mssql';
await mssql.connect('mssql://username:password@localhost/database')
const result = await mssql.query`select * from mytable where id = ${this.searcher}`

But it should still be avoided since you want to catch for errors instead of letting it crash.

In current versions of Node.js, if an await/promise rejects, and isn't caught with a .catch() , then the uncaught promise will terminate your application with the error

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