最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calling a async function - Stack Overflow

programmeradmin0浏览0评论

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
 |  Show 2 more ments

3 Answers 3

Reset to default 7

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();

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)()
发布评论

评论列表(0)

  1. 暂无评论