等待而不将功能声明为异步 [英] await without declaring function as async
问题描述
实际上,在Dart中,为了在函数体中使用await
,需要将整个函数声明为async
:
Actually in Dart, in order to use await
in function body, one need to declare whole function as async
:
import "dart:async";
void main() async {
var x = await funcTwo();
print(x);
}
funcTwo() async {
return 42;
}
如果不将main()
标记为async
Error: Unexpected token 'await'.
但是,医生说"await
表达式计算e
,然后挂起当前正在运行的函数,直到结果准备好,即直到Future完成为止"( Dart语言异步支持)
But, doc says "The await
expressions evaluates e
, and then suspends the currently running function until the result is ready–that is, until the Future has completed" (Dart Language Asynchrony Support)
那么,也许我错过了一些东西,但是没有必要强制功能异步吗?使异步声明成为必需的理由是什么?
So, maybe I miss something, but there is no need to force function to be asynchronous? What is a rationale for making async declaration obligatory ?
推荐答案
在async
函数中,await
被重写为使用.then(...)
而不是await
的代码.
In async
functions await
is rewritten to code where .then(...)
is used instead of await
.
async
修饰符将这样的功能标记为必须重写且支持await
的功能.
The async
modifier marks such a function as one that has to be rewritten and with that await
is supported.
没有async
,您将不得不写
void main() {
return funcTwo().then((x) {
print(x);
});
}
这是一个非常简单的示例,但是当使用更多异步功能(例如try
/catch
,await for(...)
,...
This is a very simple example but the rewriting can be rather complex when more of the async features are uses, like try
/catch
, await for(...)
, ...
这篇关于等待而不将功能声明为异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!