Sunday, 2 April 2017

How to export async function from a node module

I'm trying to write a node module, to handle my various db calls. I want to use async/await where ever I can, but I'm having some issues with it.

I've been using promises a bit, and export those functions fine. Example:

function GetUsernames() {
    return new Promise(function (resolve, reject) {
        sql.connect(config).then(function () {
            new sql.Request()
                .query("SELECT [UserName] FROM [Users] ORDER BY [LastLogin] ASC").then(function (recordset) {
                    resolve(recordset);
                }).catch(function (err) {
                    reject(err);
                });
        });
    });
}

And then I export in the following:

module.exports = {
    GetUsernames: GetUsernames,
    GetScopes: GetScopes,
    UpdateToken: UpdateToken,
    SetOwner: SetOwner
};

But, how should I do this, with an async function, to use the async/await that is available in node7?

Do I still just return a promise? I tried doing that, but when I then call it in my code, it doesn't work.

const db = require("dataprovider");
...
var result = await db.GetUsernames();

It gives me:

SyntaxError: Unexpected identifier

on the db name (works fine if I just use the promise functions, with then().)

Maybe my google skills are terrible, but I haven't managed to google anything I could use, on this issue.

How on earth do I make an async function, in my module, that I can await elsewhere?



via Nicolai

No comments:

Post a Comment