javascript 在主文件中调用异步函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46601552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling async function in main file
提问by Tripo
I am creating App integrating two systems. Therefore, I am using some requests and async functions. It's no problem to call async function in async function. However, I need to end somehow this chain and call async function in my main file where is App served from. Do you have any idea how to do it? Part of code looks like this
我正在创建集成两个系统的应用程序。因此,我使用了一些请求和异步函数。在 async 函数中调用 async 函数是没有问题的。但是,我需要以某种方式结束这个链并在我的主文件中调用异步函数,其中应用程序是从那里提供的。你知道怎么做吗?部分代码看起来像这样
async function asyncFunctionINeedToCall() {
await childAsyncFunction()
}
asyncFunctionINeedToCall()
Thank you for your answers!!
谢谢您的回答!!
回答by boehm_s
Since the main scope is not async, you will need to do an async anonymous function that calls your function and itself :
由于主作用域不是async,您将需要执行一个异步匿名函数来调用您的函数及其本身:
(async function() {
await yourFunction();
})();
Or resolve the promise :
或解决承诺:
yourFunction().then(result => {
// ...
}).catch(error => {
// if you have an error
})
Hope it helps,
Best regards
希望它有帮助,
最好的问候

