Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js module: export async function

In the given example it is demonstrated, how to export a variable, or a function from a custom module. How could one export an asynchronous function in a similar manner and then call it from app.js something like:

// app.js

var things = require("./someThings");

await things.getSomeThingsAsync();

EDIT:

The example (answer on Stackoverflow) pointed to by the above link contains the following code:

// someThings.js

(function() {
    var someThings = ...;

    ...

    module.exports.getSomeThings = function() {
        return someThings();
    }

}());

// main.js

var things = require("someThings");
...
doSomething(things.getSomeThings());

Say inside of the module's incapsulated function a asynchronous function exists, which you would like to expose to whoever imports the module. For example:

(function() {
    ...
    const doSomethingAsync = (time) => {
        return new Promise(resolve => {
            setTimeout(() => resolve(42), time)
        })
    }

    //const doSomething = async () => {
    async function doSomething () {
        let answer1 = await doSomethingAsync(3000)
        let answer2 = await doSomethingAsync(1000)
        return answer1 + answer2
    }
    ...
    /*module.exports.doSomething = function() {
        return doSomething();
    }*/
    module.exports.doSomething = async function() {
        return doSomething();
    }
}());

How would you expose the doSomething function in similar fashion as the in the original answer it is done for someThings - how can the referred to answer be changed in such a way, that when exporting functions, it lets you use the await keyword? It will then be used as:

// app.js

var things = require("./someThings");

console.log(await things.doSomething());

I have tried multiple approaches, but I always get:

SyntaxError: await is only valid in async function
like image 423
Alexander Avatar asked Jan 27 '23 04:01

Alexander


1 Answers

You can try this :

//yourModule.js

let yourModule={};
yourModule.you=async()=>{
    //something await...
}
modules.export = yourModule;


//app.js

let yourModule = require('<pathToModule>');

async function test()
{
    await yourModule.you();  //your `await` here
}
like image 66
Le Quang Avatar answered Jan 28 '23 17:01

Le Quang