即使代码的其余部分完成执行,JavaScript完成执行异步功能也会执行吗?

发布于 2025-02-12 14:24:26 字数 610 浏览 0 评论 0原文

这是我尝试的 -

async func1(){
 // do asynchronous calls with await
 console.log("call finished");
}

func2(){
 func1(); // without await
 console.log("func2 finished");
 return;
}

func2();

输出是 - func2完成的呼叫完成。 因此,即使在父函数完成执行之后,异步函数仍然完成了预期的目的。

如果我们将某些东西返回外部服务的API,此功能是否可以工作? 像云功能一样 -

async func1(){
 // do asynchronous calls - post db using await
 console.log("call finished");
}

func2(){
 func1(); // without await
 return response.status(200).send("");
}

func2();

即使响应。Send也会首先执行数据库,如果我不等待等待第一个完成执行的功能,则首先执行?

This is what I tried -

async func1(){
 // do asynchronous calls with await
 console.log("call finished");
}

func2(){
 func1(); // without await
 console.log("func2 finished");
 return;
}

func2();

The output was - func2 finished call finished.
So even after the parent function completed execution, the async function still completed what it was intended for.

Will this work in case of an API where we are returning something to an external service?
Like cloud functions -

async func1(){
 // do asynchronous calls - post db using await
 console.log("call finished");
}

func2(){
 func1(); // without await
 return response.status(200).send("");
}

func2();

Will the database call complete even if the response.send is executed first provided I don't await for the first function to finish execution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

〃安静 2025-02-19 14:24:26

是的,由异步函数返回的承诺只是一个句柄,它可以使您可以将逻辑链接到函数提供的异步值或时机上。您没有做任何事情。如果您不使用。然后等待链接起来,那么异步函数仍然可以运行并浏览所有代码 - 只是它返回的承诺是在其他地方使用。

也就是说,悬而未决的承诺是通常是一个坏主意 - 在大多数情况下,您可能应该链

Yes, the Promise returned by an async function is only a handle that lets you chain logic onto the asynchronous value or timing provided by the function. You don't have to do anything with it. If you don't use .then or await to chain off of it, the async function still runs and goes through all its code - it's just that the Promise it returns doesn't get used elsewhere.

That said, dangling promises are usually a bad idea - in most cases, you probably should chain a .then or .catch onto a promise.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文