Reputation: 2358
I have a module as follows:
async.js
module.exports = async function (){
await func()
}
index.js
var asyncFun = require('async')
How do i run it directly as asyncFun()
in index.js ?
I know how to run these functions as middlewares but i want to run it directly. As for running it i need to call await and await cannot be called without being inside async.
Upvotes: 3
Views: 2979
Reputation: 31833
As you are using CommonJS, you cannot use await
at top-level (contrary to ECMAScript modules) but you can get around it with this:
(async () => {
await asyncFun();
// Do something else
})();
In an ECMAScript module, since ECMAScript 2022 (ES13) it is possible to use a top-level await:
await asyncFun();
// Do something else
If you don't need to chain other instructions after the Promise
returned by asyncFun
has resolved, then you don't need await
at all:
asyncFun();
Upvotes: 7
Reputation: 2358
I solved this question by making the root function async and wrapping all the async function with a normal function and the async function returning a promise. ( using a calling).
Example :
Assume this is the main function where you write all the code.
// create it as a async function
module.exports = async function main(){
// Do something all your stuff
}
Call your main function from else where
require('./main)()
Upvotes: 0
Reputation: 624
try adding return statement in async.js
module.exports = async function (){
return await func()
}
and run asyncFun() directly
Upvotes: 0