nodejs接连运行异步功能
我是JS/nodejs的新手,所以如果我不能提出直截了当的问题,请原谅我.
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() {...}
如何确保init()完成异步请求后调用main()?
How can I make sure to call main() after init() has finished its async requests?
具体来说,我想利用该模块 https://www.npmjs.com/package/hot-import
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.
我认为问题不是常数hotMod
,而是导致问题的 async 函数中的 await hotImport.因此,我正在尝试将hotMod
定义为全局变量,并在调用 main()
之前在async init()
函数中执行hotMod = await hotImport(MODULE_FILE)
.但是到目前为止,由于我对JS/nodejs很陌生,所以我还没有做到.
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.
请帮助.谢谢.
使用aysnc等待
async function myFlow(){
.....
await init();
main();
....
}
在上面的代码中,仅当init被解析()时,才会调用main(). 希望对您有帮助.
In above code main() will be called only when init is resolved(). I hope this helps you.