How to export async function from a node module

To turn on 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 more information.

Also, just as an FYI, it a code convention to start function with lowercase, unless you are returning a class from it.


async - await pattern really makes your code easier to read. But node do not allow for global awaits. You can only await an asynchronous flow. What you trying to do is to await outside async flow. This is not permitted. This is kind of anti-pattern for node application. When dealing with promises, what we actually do is generate an asynchronous flow in our program. Our program continue without waiting for promise. So you can export your functions as async but cannot await for them outside async flow. for example.

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

Thus, async-await pattern works for async flow. Thus use them inside async functions, so that node can execute them asynchronously. Also, you can await for Promises as well. for example.

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

Here you have created async function 'fn'. This function is thenable. also you can await for 'fn' inside another async function.

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

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