即使代码的其余部分完成执行,JavaScript完成执行异步功能也会执行吗?
这是我尝试的 -
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,由异步函数返回的承诺只是一个句柄,它可以使您可以将逻辑链接到函数提供的异步值或时机上。您没有做任何事情。如果您不使用
。然后
或等待
链接起来,那么异步函数仍然可以运行并浏览所有代码 - 只是它返回的承诺是在其他地方使用。也就是说,悬而未决的承诺是通常是一个坏主意 - 在大多数情况下,您可能应该链
。
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
orawait
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.