How to export async function from node module

I am trying to write a node module to handle various db calls. I want to use async / await wherever I am, but I have some problems with it.

I used promises a bit and exported these functions. 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 the following:

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

      

But how do I do this with the async function to use the async / await available in node7?

Will I still get the promise back? I tried this, but when I call it in my code, it doesn't work.

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

      

This gives me:

SyntaxError: Unexpected identifier

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

Maybe my google skills are terrible, but I have not been able to google whatever I use for this issue.

How can I make an asynchronous function in my module that I can expect elsewhere?

+3


source to share


2 answers


To include the await keyword, you need to have it inside an async function.

const db = require("dataprovider");
...
let result = getUserNames();

async function getUserNames() {
    return await db.GetUsernames();
}

      



See http://javascriptrambling.blogspot.com/2017/04/to-promised-land-with-asyncawait-and.html for details .

Also, like FYI, it is a code convention to run a function in lower case if you don't return a class from it.

+6


source


The async - await pattern really makes your code easier to read. But the node does not allow global expectations. You can only wait for an asynchronous flow. What you are trying to do is wait outside of the async thread. This is not permitted. This is a kind of anti-pattern for the host application. When we are dealing with promises, we are effectively generating an asynchronous thread in our program. Our program continues without waiting for promises. This way you can export your functions as asynchronous, but you cannot expect them outside of the asynchronous thread. eg.

const db = require('dataprovider');
...
let result = (async () => await db.GetUserNames())();
console.log(result); // outputs: Promise { <pending> }

      

So the asynchronous wait pattern works for an asynchronous thread. Thus, use them inside asynchronous functions so that the node can execute them asynchronously. Also, you can wait for promises. eg.

let fn = async () => await new Promise( (resolve, reject)=>{...} );
fn().then(...);

      



Here you have created an asynchronous function 'fn'. This feature is available. also you can expect 'fn' inside another asynchronous function.

let anotherFn = async () => await fn();
anotherFn().then(...);

      

Here we are waiting for an async function inside an async function. The Async-Await pattern makes your code readable and concise. This is reflected in large projects.

0


source