nodejs run async function one after another

泪湿孤枕 提交于 2020-07-21 06:24:58

问题


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.


回答1:


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.




回答2:


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



回答3:


To run them synchronously, just do:

await init()
await main()


来源:https://stackoverflow.com/questions/53898917/nodejs-run-async-function-one-after-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!