admin管理员组文章数量:1406911
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.
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.
Share Improve this question edited Oct 1, 2021 at 8:31 Guerric P 31.9k6 gold badges58 silver badges106 bronze badges asked Jul 5, 2018 at 10:55 pr0ppr0p 2,33815 silver badges34 bronze badges 7- 2 You don't need to call await, just run asyncFunc(). – ChrLipp Commented Jul 5, 2018 at 10:58
-
you could just use the default promise syntax:
asyncFun().then( () => doSomething() )
– Sirko Commented Jul 5, 2018 at 10:58 - @Sirko can do that but the problem is there is a lot of code below and i need to use async to keep the code clean – pr0p Commented Jul 5, 2018 at 11:00
- I guess you don't need to wrap it inside async function in index.js just return asyncFun() or const asyncData = asyncFun() should do the work. – SAGAR RAVAL Commented Jul 5, 2018 at 11:03
- @ChrLipp that will work asynchronously. Even if i wait for the promise to resolve i do not want to use then. – pr0p Commented Jul 5, 2018 at 15:19
3 Answers
Reset to default 7As 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();
try adding return statement in async.js
module.exports = async function (){
return await func()
}
and run asyncFun() directly
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)()
本文标签: javascriptCalling a async functionStack Overflow
版权声明:本文标题:javascript - Calling a async function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744997306a2636755.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论