Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs run async function one after another

I'm new to JS/nodejs, so please pardon me if I can't ask to-the-point question.

So basically, if I have two async functions,

async function init() {...}
async function main() {...}

How can I make sure to call main() after init() has finished its async requests?

Specifically, I want to make use of the module https://www.npmjs.com/package/hot-import

whereas on its page, there is a sample code:

async function main() {
  const MODULE_CODE_42 = 'module.exports = () => 42'
  const MODULE_CODE_17 = 'module.exports.default = () => 17'

  const MODULE_FILE = path.join(__dirname, 't.js')

  fs.writeFileSync(MODULE_FILE, MODULE_CODE_42)
  const hotMod = await hotImport(MODULE_FILE)
  . . .

The sample code works as it is, but when I put that into a event call back function, things start to break -- It works for the first event trigger but not the second.

I think the problem is not the constant hotMod, but the await hotImport in async function that is causing the problem. Thus I'm trying to define hotMod as a global variable and do hotMod = await hotImport(MODULE_FILE) in a async init() function before main() is called. But so far I've not been able to, as I'm quite new to JS/nodejs.

Please help. Thx.

like image 399
xpt Avatar asked Oct 26 '25 15:10

xpt


2 Answers

using aysnc await

async function myFlow(){
.....
await init();
main();
....
}

In above code main() will be called only when init is resolved(). I hope this helps you.

like image 153
Varun Sukheja Avatar answered Oct 28 '25 05:10

Varun Sukheja


async function return promises. So you should be able to call one after the other with then()

init()
.then(() => main())

If init returns something (for example hotMod), you can pick it up as a parameter to then's callback.

init()
.then((init_return) => {
   // do something with init_return
   return  main()
})
like image 44
Mark Avatar answered Oct 28 '25 05:10

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!