我正在了解 async
和await
在达特中。在大多数情况下,这是一种表示某些函数需要一段时间并且程序应该异步运行特定函数的方式。
我不明白的是这如何影响最终导致给定异步函数的所有“前面”函数。
例如,
import 'dart:async';
Future<String> firstAsync() async {
await Future<String>.delayed(const Duration(seconds: 2));
return "First!";
}
String secondAsync() async {
var returnVal = await firstAsync();
return returnVal;
}
void main() {
var s = secondAsync();
if (s == "First!") {
///run some code...
}
print('done');
}
firstAsync
返回一个 future,因此该函数的返回值为Future<String>
是有道理的。 。然后,secondAsync
使用此功能。这是否意味着secondAsync
还必须返回Future<String>
?是
main
需要async
关键字,我需要将其第一行更改为var s = await secondAsync();
?如果是这样,是否意味着
main
还需要标记为返回Future<void>
?
最佳答案
If my function calls an asynchronous function, does that force me to make my function return a Future?
不一定,但几乎总是如此。如果您的函数需要返回一个依赖于被调用的异步函数的结果,那么您的函数也是隐式异步的,并且必须返回 Future
.
如果函数的调用者不需要在函数完成时收到通知,那么您的函数是 "fire-and-forget" and can return void
instead of a Future
。或者,如果您的函数不依赖于被调用的异步函数(即,您正在调用“即发即忘”异步函数),那么您的函数可以返回它想要的任何内容。它不会等待任何事情。
firstAsync
returns a future, so it makes sense that the function's return value isFuture<String>
. Then,secondAsync
uses this function. Does that mean thatsecondAsync
must also returnFuture<String>
?
是的。
- Does
main
need theasync
keyword and would I need to change its first line tovar s = await secondAsync();
?
技术上不行(您可以直接使用原始 Future
API 而不是使用 await
),但您应该更喜欢使用 async
/await
。更容易理解。
- And if so, does that mean that
main
also needs to be marked as returningFuture<void>
?
main
通常没有调用者需要等待它完成(Dart VM/运行时将等到事件队列为空后再退出),所以 main
通常可以认为是一劳永逸并且可以返回 void
。目前推荐来自 avoid_void_async
lint documentation就是不去打扰main
返回 Future
.
有main
返回 Future
如果您有递归 main
,可能很重要函数或者如果你的 .dart
文件可能是import
由另一个直接调用您的 main()
的文件编辑功能。然而,这些情况非常罕见(并且最好通过重构来避免)。
关于android - 如果我的函数调用异步函数,是否会迫使我让我的函数返回 Future?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72386335/